Reflection and Generic Collections

Hi -
I'm having trouble with reflection on Sets
I have a set of type T extends U and want to return the class of T:
public static <T extends U> Class<T> getSetType(Set<T> set) {
// what to do?
}Any help?
Message was edited by:
[email protected]

parameterized types are not present at runtime, as danny basically indicated. what you want to do here is neither a generics nor a reflection issue: unless the Set is empty, you can just examine the first object it contains for it's class:
public static <T extends U> Class<T> getSetType(Set<T> set) {
     if ( null == set ) {
        return null;
     if ( 0 == set.size() ) {
        return null;
     return set.iterator().next().getClass();
}

Similar Messages

  • Reflection and generics

    Hi all:
    I am working with the generic and reflection stuff. Well the problem is that in one of my clases I have a data
    private Vector<nAryNode<T>> childs;
    .....where nAryNode<T> is a class I created using generics.
    Now when I want to initialize my childs variable, well the easy thing to do is:
    childs = new Vector<nAryNode<T>>(3)But I want to initialize it using reflection and my code is:
            Class v = Class.forName("java.util.Vector");
            Class[] argVector = new Class[] {int.class};
            Constructor consVector = v.getConstructor(argVector);
            Object[] arguments = new Object[] {new Integer(n)};
            childs = (Vector<nAryNode<T>>)consVector.newInstance(arguments);Finally when I compile I got the annoying warning message
    nAryNode.java:29: warning: [unchecked] unchecked cast
    found : java.lang.Object
    required: java.util.Vector<nAryNode<T>>
    childs = (Vector<nAryNode<T>>)consVector.newInstance(arguments);
    ^
    Well my program can run, but I would like to make disappear that message. Please if you have any suggestions for me, it will be great. Thx

    AFAIK, there is no solution to this currently because arrays of generic types are not allowed. Therefore "consVector.newInstance(arguments);" return a Vector and cannot be made to return "Vector<Integer>" (or whatever)

  • Problem in generic value copier class / reflection and generic classes

    Hello experts,
    I try to archive the following and am struggling for quite some time now. Can someone please give an assessment if this is possible:
    I am trying to write a generic data copy method. It searches for all (parameterless) getter methods in the source object that have a corresponding setter method (with same name but prefixed by "set" instead of "get" and with exactly one parameter) in the destination object.
    For each pair I found I do the following: If the param of the setter type (T2) is assignable from the return type of the getter (T1), I just assign the value. If the types are not compatible, I want to instantiate a new instance of T2, assign it via the setter, and invoke copyData recursively on the object I get from the getter (as source) and the newly created instance (as destination). The assumption is here, that the occurring source and destination objects are incompatible but have matching getter and setter names and at the leaves of the object tree, the types of the getters and setters are compatible so that the recursion ends.
    The core of the problem I am struggling with is the step where I instantiate the new destination object. If T2 is a non-generic type, this is straightforward. However, imagine T1 and T2 are parametrized collections: T1 is List<T3> and T2 is List<T4>. Then I need special handling of the collection. I can easily iterate over the elements of the source List and get the types of the elements, but I can not instantiate only a generic version of the destinatino List. Further I cannot create elements of T4 and add it to the list of T2 and go into recursion, since the information that the inner type of the destination list is T4 is not available at run-time.
    public class Source {
       T1 getA();
       setA(T1 x);
    public class Dest {
       T2 getA();
       setA(T2 x);
    public class BeanDataCopier {
       public static void copyData(Object source, Object destination) {
          for (Method getterMethod : sourceGetterMethods) {
             ... // find matching getter and setter names
             Class sourceParamT = [class of return value of the getter];
             Class destParamT = [class of single param of the setter];
             // special handling for collections -  I could use some help here
             // if types are not compatible
             Object destParam = destination.getClass().newInstance();
             Object sourceParam = source.[invoke getter method];
             copyData(sourceParam, destParam);
    // usage of the method
    Souce s = new Source(); // this is an example, I do not know the type of s at copying time
    Dest d = new Dest(); // the same is true for d
    // initialize s in a complicated way (actually JAX-B does this)
    // copy values of s to d
    BeanDataCopier.copyData(s, d);
    // now d should have copied values from s Can you provide me with any alternative approaches to implement this "duck typing" behaviour on copying properties?
    Best regards,
    Patrik
    PS: You might have guessed my overall use case: I am sending an object tree over a web service. On the server side, the web service operation has a deeply nested object structure as the return type. On the client side, these resulting object tree has instances not of the original classes, but of client classes generated by axis. The original and generated classes are of different types but have the identically named getter and setter methods (which again have incompatible parameter types that however have consistent names). On the client side, I want to simply create an object of the original class and have the values of the client object (including the whole object tree) copied into it.
    Edited by: Patrik_Spiess on Sep 3, 2008 5:09 AM

    As I understand your use case this is already supported by Axis with beanMapping [http://ws.apache.org/axis/java/user-guide.html#EncodingYourBeansTheBeanSerializer]
    - Roy

  • SCJP Preparation And Collection ,Thread And Generics Preparation Guidence

    I m preparing the SCJP 5 , I need the sources for preparing collection , thread and generics in SCJP 5.0

    Sun_Pravin wrote:
    I m preparing the SCJP 5 , I need the sources for preparing collection , thread and generics in SCJP 5.0Buy a book.

  • Generics via reflection and newInstance()

    I'm looking for a way, or a correct syntax, for 'genericizing' the
    class instantiation via Class#newInstance() method using reflection.
    The code shown below is an half-baked solution in that compiler emits
    unchecked cast warning against the cast on the 'obj' variable at the
    last part of the code.
    I think I have tried everyting conceivable for Class variable declarations
    and other part of the code but they were all futile. I lost one night
    sleep for that.
    If there are Java Generics gurus on the forum, please help!
    TIA.
    import java.util.*;
    import java.lang.reflect.*;
    public class GetMethod{
      public static void main(String[] args) {
        Object obj = null;
        Class<Hashtable> clazz = Hashtable.class;
        Class<Class> claxx = Class.class;
        try {
          Method method = claxx.getMethod("newInstance");
          obj = method.invoke(clazz);
        catch (Exception e) {
          e.printStackTrace();
        Hashtable<String,String> ht = (Hashtable<String,String>)obj;
        ht.put("foo", "bar");
        System.out.println(ht.get("foo"));
    }

    If you are preparing teaching material, then I would strongly suggest that you do not mix generics with reflection until both are very well understood.
    Using reflection to invoke reflection API methods (or any method known at compile time) as you did in your example, suggests that you do not understand enough yet.
    Because generics are a compile time mechanism and reflection is run time, many of the naive assumptions you might make just wont hold. Reflection is a mechanism for subverting the compiler, don't expect reflection and the compiler to have a harmonious relationship.
    Please remember when writing training material, that the code you use will be assumed by your students to be the best way to solve the problem it purports to solve. You need to bear this in mind when choosing code samples, not only must the sample illustrate the feature being taught, but it must be an appropriate application of that feature. If you do not choose appropriate problems to solve with your illustrative code, you will unwittingly train a generation of incompetents, whose code will be even stupider than yours.
    Bruce

  • variable-class using Generic Collection

    Within my TLDs I would like to use the <variable-class> attribute as much as possible for the sake of JSP authors.
    I cannot figure out how to specify that a varAttribute will be a generic collection. IE, if I want to return a set of strings, I would like to do
    <variable-class>
    java.util.set<java.lang.String>
    </variable-class>
    Of course I must escape the <,> and I tried using < and > but it was not effective.
    Is this even possible? I would appreciate any comments suggestions.

    Currently we are using a single domain account on every machine in this kiosk area. They are using just Internet Explorer and Adobe Reader. We are using Group Policy to lock down the machines. Each station is a full computer (older Dell OptiPlex) running
    Windows 7. We are looking at the possibility of removing the OptiPlex computers and replacing them with Wyse terminals. The backend would be a cluster of 3 servers running Hyper-V 2012 R2. On those would be running Windows Server 2012 R2 RDS.  We have
    tested this setup, but when creating the VDI collection there doesn't seem to be a way to use generic domain accounts. 
    Every person that uses these does not have an AD account and it looks like that would be a problem when trying to implement this.  I was just checking here to see if anyone had any ideas or had gone through a similar setup.

  • OAM Generic Collection Services

    Hi,
    After cloning from multi node to single node, OAM Generic Collection Service is not started by default ?
    However, i manually started it.
    Is this the normal
    Thanks
    sunil

    Sunil,
    What is the error?
    Please clean FND_NODES table as follows, and run AutoConfig on the database/application tiers then:
    SQL> EXEC FND_CONC_CLONE.SETUP_CLEAN;
    SQL> COMMIT;If the above does not help, please have a look at [Note: 393706.1 - OAM Generic Collection Service shows State: The target node/queue unavailable|https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=393706.1]

  • Difference between Customer Generated Extractors and Generic Extractors

    Hi all,
            Can anyone please tell me the difference between Customer Generated Extractors and Generic Extractors.  I know that for all modules Generic extraction is possible by creating a datasource(RSO2) on top of a table, View or SAP Query in SE11.  What are customer generated extractors like LIS, CO/PA and FI/SL. 
    What kind of extraction is used for FI/AR and FI/AP.  To my understanding we have BW Content Extractors.  Can anyone explain the extraction method and delta extraction for AR and AP.
    Thanks,
    Sabrina.

    Hi,
    Customer generated extractors are running on top of statistics data collection process in R/3. They extract data from statistical tables already available in R/3 and also use the mechanism already provided in R/3 to capture the delta.
    For example, PO data goes to statistical table S012 (it is an LIS table) and you can build a generated extractor on top of it. The difference between such extractor and a generic one is the fact that these extractors (eg LIS) use the same mechanism of capturing delta that the statistics table was doing (for example data that goes into S012 is also captured by these generated extractors). Some system tables and structures are generated automatically to support this functionality, you do not have to develop anything for this.
    Generic extractors on the other hand simply let you pull data from table/view/query etc. You have to develop code/functionality to support delta capturing for such extractors. If you built a generic extractor on top of S012 (it is a statistical table - LIS), you can pull its data to BW, but you do not have the delta capturing functionality in such case, you will have to code it yourself.
    As a thumb rule, you go with the standard/generated extractors, and use generic extractors only if it is necessary to be so.
    FI/AR and FI/AP extractors are part of business content (I think) and support delta functionality. To get detailed info on these, you can also look at help documentation -
    http://help.sap.com/saphelp_nw04/helpdata/en/ee/cd143c5db89b00e10000000a114084/frameset.htm
    cheers,

  • Line items  AND GENERIC EXTRACTION

    what does line items exactly mean in DATASOURCES
    AND WHAT ARE DELTA TYPE EXTRACTIONS IN GENERIC
    TIME STAMPING
    CALENDAR DAY
    NUMERICAL POINTER
    COULD ANY PLEASE EXPLAIN THE DIFFERNCE  AND IN WHAT SCENARIOS WE USE IT ...
    LOOKING FOR YOUR REPLY

    Hi Guru,
    Check below doc & thread for Line Item Dimension:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/a7f2f294-0501-0010-11bb-80e0d67c3e4a
    Line Item Dimenstion
    If a field (date, progressive document number, timestamp) exists in the extract structure of a DataSource that contains values which increase monotonously over time, you can define delta capability for this DataSource. If such a delta-relevant field exists in the extract structure, such as a timestamp, the system determines the data volume transferred in the delta method by comparing the maximum value transferred with the last load with the amount of data that has since entered the system. Only the data that has newly arrived is transferred.
    To get the delta, generic delta management translates the update mode into a selection criterion. The selection of the request is enhanced with an interval for the delta-relevant field. The lower limit of the interval is known from the previous extraction. The upper limit is taken from the current value, such as the timestamp or the time of extraction. You can use security intervals to ensure that all data is taken into consideration in the extractions (The purpose of a security interval is to make the system take into consideration records that appear during the extraction process but which remain unextracted -since they have yet to be saved- during the next extraction; you have the option of adding a security interval to the upper limit/lower limit of the interval).
    After the data request was transferred to the extractor, and the data was extracted, the extractor then informs generic delta management that the pointer can be set to the upper limit of the previously returned interval.
    To have a clear idea:
    1. If delta field is Date (Record Create Date or change date), then use Upper Limit of 1 day.
    This will load Delta in BW as of yesterday. Leave Lower limit blank.
    2. If delta field is Time Stamp, then use Upper Limit of equal to 1800 Seconds (30 minutes).
    This will load Delta in BW as of 30 minutes old. Leave Lower limit blank.
    3. If delta field is a Numeric Pointer i.e. generated record # like in GLPCA table, then use
    Lower Limit. Use count 10-100. Leave upper limit blank. If value 10 is used then last 10
    records will be loaded again. If a record is created when load was running, those records
    may get lost. To prevent this situation, lower limit can be used to backup the starting
    sequence number. This may result in some records being processed more than once.
    Refer this link from help.sap.com
    http://help.sap.com/saphelp_erp2005/helpdata/en/3f/548c9ec754ee4d90188a4f108e0121/frameset.htm
    Difference between timestamp used in copa and generic data extraction?
    COPA timestamps vs Generic timestamps
    Check this doc for more info:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/84bf4d68-0601-0010-13b5-b062adbb3e33
    Hope these helps u...
    Regards,
    KK.

  • Report to list all computers and their collection membership

    Hi
    I am currently working on a site where direct membership is used for collections but a need has arisen to move to AD Queries.
    I have created a simple powershell script that creates groups based on the contents of a csv file and another script which populates this with the members listed in another csv file.
    To help speed up the process is there a way to generate a report that lists ALL Computers and their Collection membership?
    The only reports I seem to find that are built in require an inputted value of either computer name of collection ID. I simply need a report that lists Computer Name is column 1 and Collection Name in column 2 for all computers and all collections.
    Many Thanks,
    Matt Thorley

    select 
    FCM.Name,
    C.Name
    from 
    dbo.v_Collection C
    join dbo.v_FullCollectionMembership FCM on C.CollectionID = FCM.CollectionID
    Thanks to Garth for original query. I just modified it :)
    Anoop C Nair (My Blog www.AnoopCNair.com)
    - Twitter @anoopmannur -
    FaceBook Forum For SCCM

  • How to get the Folders and subfolders collection in Project Manager

    Hi,
    I am trying to get the folders and subfolders collection in Project Manager, so that I will be able to loop through the collection and be able to create a project under the appropriate folder.
    Any suggestions?
    Thanks.
    Bhanu

    Anything you do without submitting to form has to be done on the client side (ususally by JavaScript) using data which has been send already from the server.
    With JavaScript you can do quite a bit. You can download tables which don't necessarilly appear on the screen, loading them into JavaScript arrays by dynamically generating javascript. Then you can pick up events like drop-box selection and use these tables to chose what you do next (e.g. preloading other fields, setting drop box content etc.).
    Or, you can cause forms to be submitted when actions like a selection happen without the user clicking a button. It's generally a matter of how much data you'd need to transmit.
    Another posibility is to use a Java applet, which can generate requests to the server and handle the results as it chooses. That are a number of problems with that but occasionally it's the best solution.
    What you can't do is to handle user input inside a JSP. The JSP has come and gone before the user even gets to see your form.

  • SystemManager and Garbage Collection

    Hi everyone, I have a question regarding the SystemManager and Garbage Collection. I have and application that loads in its assets via a swc created in Flash. In that swc I have different MovieClips that act as the different screens of my application each one being tied to its own custom class. For example one MovieClip is a login screen another is the main menu etc. These screens contain components, text fields and animations. The problem that I am having is when I move from one screen to the other the garbage collector is not cleaning up everything. There are still references to the MovieClips that have animations for example. So even though I remove the screen via removeChild and set the variable reference to that object to null it is not releasing the MovieClips. When I pull it up in the profiler it shows me that SystemManager is holding references to them. Also if I debug the applicaion and look inside the instance of the MovieClip I can see that the private property "listeners" has values, but I am not adding listeners. It appears that the SystemManager is adding listeners. Does anyone know how I can clear these listeners or force the SystemManager to release these items. Any ideas or help would be greatly appreciated. I am fairly new to dealing with memory management and garbage collection in Flex. I am using Flash CS4 to create the swc and Flash Builder 4 Beta with the 3.4 framework and Flash Player 10 to create the app. If you need me to clarify any of this please let me know. Again any help or ideas on where to go from here would be great!

    This chain says that the focusManager is referencing UserMenu.  Is there a default button or focusable objects in UserMenu and references from UserMenu to the objects in question?
    BTW, the CS4 fl.managers.FocusManager and any fl.. classes are incompatible with Flex, so make sure you're not using them in your MovieClips.
    Alex Harui
    Flex SDK Developer
    Adobe Systems Inc.
    Blog: http://blogs.adobe.com/aharui

  • USING IF IN FORALL AND BULK COLLECT

    Hi All,
    I wrote an program..I have doubt whether i can use if condition in FORALL INSERT OR BULK COLLECT? I can't go for 'for loop' ....Is there any way to to do validations in FORALL INSERT and BULK COLLECT like we do in 'for loop' ...
    create or replace
    PROCEDURE name AS
    CURSOR CUR_name IS
    SELECT OLD_name,NEW_name FROM DIRECTORY_LISTING_AUDIT;
    TYPE V_OLD_name IS TABLE OF DIRECTORY_LISTING_AUDIT.OLD_name%TYPE;
    Z_V_OLD_name V_OLD_name ;
    TYPE V_NEW_name IS TABLE OF DIRECTORY_LISTING_AUDIT.NEW_name%TYPE;
    Z_V_NEW_name V_NEW_name ;
    BEGIN
    OPEN CUR_name ;
    LOOP
    FETCH CUR_name BULK COLLECT INTO Z_V_OLD_name,Z_V_NEW_name;
    IF Z_V_NEW_name <> NULL THEN
    Z_V_OLD_name := Z_V_NEW_name ;
    Z_V_NEW_name := NULL;
    END IF;
    FORALL I IN Z_V_NEW_name.COUNT
    INSERT INTO TEMP_DIREC_AUDIT (OLD_name,NEW_name) VALUES (Z_V_OLD_name(I),Z_V_NEW_name(I));
    EXIT WHEN CUR_name%NOTFOUND;
    END LOOP;
    CLOSE CUR_name;
    END name;

    FORALL i IN v_tab.FIRST .. v_tab.LAST
             INSERT ALL
                WHEN v_tab (i) = 1
                THEN
                   INTO sen_temp
                        (col_num
                 VALUES (v_tab (i) + 5
                SELECT dummy
                  FROM DUAL;
          EXIT WHEN c1%NOTFOUND;this is the one u looking for i guess...

  • Measure Formulae for Uploadable and Data collection report

    Hi,
    I have query related to application of measure Formula for Uploadable and Data collection report.
    Consider a scenario where i use a MDX query to create a data collection report and I map these columns from these reports to an rowsource using a loader file. Can I use measure formula feature like onchange to work with Uploadable and Data colection reports such that changes to any one column should take effect in another column.
    Regrads,
    Wesley

    Wesley,
    IOP uploadable reports are used for sending data to the server in batch. They are coupled to the IOP model via a rowsource. You have a lot of flexibility with the spreadsheet you build for staging the upload. It's really just a function of how crafty you are with vb. Cascading changes from one column to another can be easily accomplished this way.
    Onchange formulas are for something else. They are part of the model definition and are used for describing how to cascade changes between IOP data blocks.

  • Customer and Generic extraction difference ?

    Hi ya,
    Could any body tell me the difference between the customer and Generic extractions.what are the extraction steps?
    Regards.
    H

    Hi,
    In Generic extraction we have to fetch the data from table/view/funtion module.T.code RSO2.
    Replicate the data source in bw and send into data target through ods(recommandable).
    In customized extraction sap provided LIS,LO-COCKPIT,CO-PA,FI-SL etc,in these sap provides extract stuructures.From the extract structures we have to fetch the data and replicate the data into bw and push into the data targets.
    with regards,
    HARI GUPTA

Maybe you are looking for

  • Smartform error while issue printpreview in billing

    Hello SAP Consultant... Problem: "Graphic cannot be displayed" while choose output type and print preview in billing VF03. What I did: I developed one invoice smartform in development and transport to production, working properly.By mistake i deleted

  • Backing up iPhoto pics without using Time Machine or an external hard drive

    I cannot figure out how to back up my photos on my one year old MBP. I haven't gotten around to buying an external hard drive (so many choices and there seems to be problems with every one I look at - advice?), but at this time the only important dat

  • How to include .jars?

    Hello, I have been unable to find out how to include in the .ear file generated by wsgen the supporting .jar files that my Web Service EJB needs. I thought this could be done with the "classpath" parameter in the wsgen tag in build.xml, but it doesn'

  • Problems gifting playlist - order randomized and Error 1008

    I can purchase music fine, so I know my account is indeed working. But when I try to gift a playlist via the iTunes Store, 2 errors keep occuring: 1. Track order gets randomized. (Not that it'd matter, but I don't have shuffle checked.) Each time I t

  • Tethered Modem

    Does anyone know if Apple Supports using the iPhone as a tethered modem? I see several sites where you have to hack into the iPhone but I'd rather not do that. Unfortunately I live in an area where High Speed is not available, I am able to get up to