Getting generic type at runtime

Example:
public class GenericTest {
private List<String> list = new List<String>();
How can I get the type String at runtime?
Class c = GenericTest.class;
Field[] fiels = c.getFields();
for (Field f: fields) {
Class fc = f.getDeclaringClass();
// What are the next steps to to get String.class from fc?
}

Generic types (ie. the ones inside the < >) get Erased at compile-time. All this type information is therefore not available at run-time
Google "Java Generics Erasure" to get some more info. (There's a Generics forum by the way!)

Similar Messages

  • Generics' types at runtime (JVM)

    Hi everybody
    This is gonna be a tricky question I guess.
    I'm using generics for an application of mine and I need to know the actual types of a class at runtime.
    For example, let's say I have: "Hashtable<String, Integer> ht;"
    Using Reflection I can easily find out that 'ht' is an 'Hashtable' as well as I can create an instance of Hashtable.
    But if I use 'ht.getTypeParameters()' to find out the type of the generics, I get '<K,V>' instead of
    '<String,Integer>', this because 'ht.getTypeParameters()' returns the formal types and not the actual types.
    In the same way, "Class.forName("java.util.Hashtable");" works, while
    "Class.forName("java.util.Hashtable<String,Integer>");" throws an exception because it can't find the class,
    Does anybody of you know if and how it is possible to access actual generics types at runtime?
    Thanks in advance
    michele

    Not possible. That's why we call it erasure ;-)
    There is an RFE to reify generic type arguments at runtime:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5098163

  • Getting value type at runtime

    Hello everyone,
    I am using Scanner to get tokens from a buffer. I need to know the type (class) of the value returned. Instead of using "if" statement and hasNext?() for each possible type, is there a method that just return the type. Something like:
    Class c = get(String s);So, if s is "Address", c would be set to String.class. If s is "true", c would be set to Boolean.class... etc
    Thank you

    Yeh, I just saw your other post:
    http://forum.java.sun.com/thread.jspa?threadID=783200
    The two topics are different but related. The topic, you refer to, are taking about getting a value. In that topic I need a method like:
    Object o = String.toObject (String s, Class c);However, the topic "Getting value type at runtime" are taking about getting a type. In this topic I need a method like:
    Class c = string.getClass();to return the type this string represents.

  • Instantiation of generic type

    Hi.
    I have an issue with instantiating of generic type. My issue is similar to this Re: creating instance of generic type post.
    So I have the following class
    public class VehicleForm<V extends Vehicle>{
    private V vehicle;
    private Double price;
    private Class<V>vItemClass;
    public V getVehicle(){
    return this.vehicle;
    public void setVehicle(V vehicle){
    this.vehicle=vehicle;
    public Double getPrice(){
    return this.price;
    public void setPrice(Double price){
    this.price=price;
    private final Class<V> getGenericClassInstance() {
    Class<V> persistentClass = null;
    Type genericType = getClass().getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
    ParameterizedType pType = ((ParameterizedType) genericType);
    // obtaining first generic type class
    persistentClass = (Class<V>) pType.getActualTypeArguments()[0];
    return persistentClass;
    public VehicleForm(){
    this.vItemClass=getGenericClassInstance();//vItemClass is null
    this.vehicle=this.vItemClass.newInstance();//null poiner exception
    I cannot write in default constructor
    public VehicleForm(){
    this.vehicle=new V();//runtime error will occure
    because of generic type
    For obtaining generics we can use java reflection functionality. Generic type list in runtime is obtaining through ParameterizedType. The code in getGenericClassInstance is standard to instantiate generic type var.
    But unfortunately in my case it doesn't work. getGenericClassInstance returns null. Line Type genericType = getClass().getGenericSuperclass(); doesnt get generic type which is instance of ParameterizedType, so the condition if (genericType instanceof ParameterizedType) is false. My genericType is Object instance, but not ParameterizedType. So I cannot create Class<V> instance from null.
    Can anybody help me? Thanks in advance.
    Edited by: 877736 on 06.08.2011 12:50
    Edited by: 877736 on 06.08.2011 12:51

    877736 wrote:
    My issue is similar to this Re: creating instance of generic type post...Did you look at the answers given there? Pretty much the same as ttjacobs is telling you here: This is NOT what generics was created for.
    Even if you can do it, the code is likely to be messy, complex and brittle.
    Also: this thread is in the wrong category, as the other poster (you?) was already told. There is a "Generics" section under Java APIs.
    My suggestion: rethink your solution.
    Winston

  • Get the Type of a generic field at runtime, How to?

    Hello,
    As the topic already says, i need to get the Type of a particular field of a class. This field is declared private and generic. In C# there is a method
    Type Object.getTypeIs there any specific way to do this in Java 1.5?
    Please excuse my poor english.
    Thanks in advance.
    Markus

    McNepp wrote:
    endasil wrote:
    McNepp wrote:
    If you want to know the parametrized type (String in the example), I think there is no way of knowing this in Java 1.5 or Java 1.6, since the parametrized type is erased and not available at run time.The type of a parameterized field is not erased.For most intents and purposes, it is. Type erasure refers to the fact that at runtime, there are not actually multiple class binaries depending on the generic arguments to a class. Therefore, an ArrayList<T> is actually just an ArrayList with no generics.
    Frankly, I don't understand why you insist that the information on generic fields that the OP was asking about is lost at runtime.I wasn't trying to insist that. At the time, I was replying more to Saish and trying to reaffirm that most information about generics is lost at run-time. I mistakenly ignored how you qualified it with "field."
    What you write about instances of generic classes losing their type information is of course correct, albeit not to the point of the original question.Nope, you're right. I was just trying to reconcile the fact that many people get confused that there's any information available at run-time, and so start down the path of thinking that type erasure doesn't exist. But it very much does.
    The original question was about how to obtain the type of a generic field.And I did show in my example that even that is fairly limited, given that if the type is provided by the parameter of the class, it doesn't give you anything useful (I'm not trying to say you said it would!).
    The compiler preservers this information in the class file, so it can be obtained at runtime. Frameworks like JPA put this to use extensively, proving that it is of real value.Definitely. However I don't see this having as much to do with generics as basic reflection functionality. If you can get the type of a field at run-time, you should be able to get the parameters as well! That should in no way belittle its value, though. But I would have guessed (knowing little about) that JPA wouldn't put that to use so much as the type parameters of an accessor return type or mutator argument type. Especially since I thought we'd shown that you would need your fields to be non-private for JPA to be able to gain information about their type.
    Edit: getDeclaredField works fine with private members, and returns the expected "java.lang.String" from jschell's example above
    Edited by: endasil on 28-Apr-2009 10:39 AM

  • Java5: Can't find a way to get rid of warnings about generic types

    Hi all,
    i have this method:
        public static void insert(List list, int index, Object obj) {
            list.add(obj);
            int j = list.size() - 1;
            for (; j > index; j--) {
                list.set(j - 1, list.get(j));
            list.set(index, obj);
        }I get 3 warnings. All about:
    Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized
    I can't find a way to rewrite this method (Java5), that i get no warnings compiling it and calling it with:
    List<AnyClass> list = new ArrayList<AnyClass>();
    list.add(new AnyClass());
    AnyClass ac = new AnyClass();
    insert(list, 0, ac);May be you know another way to insert an element to a List?
    Thanks

    Never tried it and do not have 5.0 installed to test
    it, but what if you define the ArrayList as follows?
    List<Object> list = new ArrayList<Object>();
    That should get rid of the warnings.

  • Define table type on runtime...Getting Error..

    My requirement is to
    I am trying to define table type on runtime. i.e. ortf_in_table_tbl{noformat}({noformat}i).field_position_rec.ortf_segment_field_name in below code.
    But when I am executing below code and getting below error:
    DECLARE
       CURSOR field_position_cur (p_table_name VARCHAR2)
       IS
          SELECT xosf.field_name, xosf.starting_position, xosf.field_length
            FROM record_types xort, record_segments xors, segment_fields xosf
           WHERE xort.record_type_id = xors.record_type_id
             AND xors.record_segment_id = xosf.record_segment_id
             AND xosf.table_name = p_table_name;
       CURSOR raw_data_cur
       IS
          SELECT *
            FROM raw_data;
       TYPE raw_data_typ IS TABLE OF raw_data_cur%ROWTYPE
          INDEX BY BINARY_INTEGER;
       TYPE table_typ IS TABLE OF emp%ROWTYPE
          INDEX BY BINARY_INTEGER;
       table_tbl      table_typ;
       raw_data_tbl   raw_data_typ;
    BEGIN
       OPEN raw_data_cur;
       LOOP
          FETCH raw_data_cur
          BULK COLLECT INTO raw_data_tbl;
          EXIT WHEN raw_data_tbl.COUNT = 0;
          FOR i IN raw_data_tbl.FIRST .. raw_data_tbl.LAST
          LOOP
             FOR field_position_rec IN field_position_cur ('EMP')
             LOOP
                table_tbl (i).field_position_rec.field_name :=
                   SUBSTR (raw_data_tbl (i).raw_line_text,
                           field_position_rec.starting_position,
                           field_position_rec.field_length
                DBMS_OUTPUT.put_line
                        (   'table_tbl (i).field_position_rec.field_name '
                         || table_tbl (i).field_position_rec.field_name
             END LOOP;
          END LOOP;
       END LOOP;
       CLOSE raw_data_cur;
    FORALL i IN table_tbl.FIRST .. table_tbl.LAST
          INSERT INTO emp
               VALUES (table_tbl (i)
       COMMIT;
    EXCEPTION
       WHEN OTHERS
       THEN
          DBMS_OUTPUT.put_line ('OTHERS ' || SQLERRM);
    END;
    **ORA-06550: line 61, column 52:**
    **PLS-00302: component 'FIELD_POSITION_REC' must be declared**
    **ORA-06550: line 54, column 13:**
    **PL/SQL: Statement ignored**Here field_position_cur is giving me column name for the EMP table (i.e. field_position_rec.field_name) and field_position_cur is giving start and length to derive value of the that column
    i.e.
    SUBSTR (raw_data_tbl (i).raw_line_text,
                           field_position_rec.starting_position,
                           field_position_rec.field_length
                          )But it is giving me error. We are on 10g database.
    Please suggest the solution to it.
    Edited by: BluShadow on 12-Jan-2012 08:21
    added {noformat}{noformat} and other tags to make it readable.  Please read {message:id=9360002} and learn to do this yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    piyushgupta wrote:
    My requirement is to
    I am trying to define table type on runtime. Please explain - it is not clear from the code what you are attempting.
    Also note that PL/SQL is strong typed language. This mean that you cannot define a variable using a weak type and at runtime change that into a formal data type.
    In Oracle, the abstract AnyData data type can be used for unknown data types - and methods exist that allows different data types to be stored and retrieved as AnyData types. Of course, there are overheads involved in using an abstract data type (implemented as an object class) like this.
    Another method is to use DBMS_SQL to create dynamic code (SQL or PL/SQL) - and perform dynamic binding (the bind determines the data type of the bind variable in the code). If the dynamic code is a SQL select, the describe interface enables you to determine the content (columns and data types) of the SQL projection.
    The final method that comes to mind is using a RTTI (Run Time Type Information) interface - something that is also supported by Oracle (and basically the backend implementation of answering a describe interface call). This is however a bit more complex and quite specialised and needs a very unique problem to justify it being used.

  • Retrieving generic type and letter

    Hi,
    I have a generic class -
    public class AAA <T extends BBB>implements Serializable From which I want to get its generic type (the easy part),
    and the generic type letter representation (In this case - T).
    Can I do this by reflection? If so how,
    Otherwise - is there any way I can do that which doesn't involve parsing the class as text?
    Thanks,
    Sharon.

    Class.getGenericDeclaration() should lead you to the letter T.
    The actual runtime type cannot be obtained because of erasure.
    If the class is under your control, you can play a trick:
    add to the constructor(s) a Class parameter and pass the actual type
    used.

  • Creating instance of generic type

    Hi.
    Here is my class
    public class ManagerForm<M extends Stuff>{
    private Class<M>clazz;
    private M manager;
    public void setWorker(M manager){
    this.manager=manager;
    public M getWorker(){
    return this.manager;
    private final Class<M> getGenericClass() {
    Class<M> persistentClass = null;
    Type genericType = getClass().getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
    ParameterizedType pType = ((ParameterizedType) genericType);
    // obtaining first generic type class
    persistentClass = (Class<M>) pType.getActualTypeArguments()[0];
    return persistentClass;
    public ManagerForm(){
    this.clazz=getGenericClass();
    this.manager=this.clazz.newInstance();
    In default constructor I need to inicialize U instance this.user.
    I have an nullPointerException in line this.manager=this.clazz.newInstance();
    persistantClass is returned nullable because genericType is not instance of ParameterizedType.
    Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable.
    Thanks in advance.

    YoungWinston wrote:
    877715 wrote:
    Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable. I think you need to back up and explain exactly what you're trying to do here.
    It would appear that you're attempting to divine the actual type of a specific ManagerForm, but I'm not absolutely certain. Also, since you already specify the type as a field, why can't you just usemanager.getClass()? I suspect that all you'll get from getClass().getGenericSuperclass() is 'Stuff', but I have to admit I'm no expert on this.
    Far better to describe what you want than an implementation that plainly doesn't work.
    WinstonWell. I have class ManagerForm<M extends Stuff>. there is private field manager that have generic type M. And I need to instantinate manager in default constructor.
    I cant write
    public ManagerForm(){
    this.manager=new M();//will be compiler error
    Thats why exists a mechanism to get current generic type in runtyme through ParameterType.
    I have method getGenericClass that gets current class in runtime and then I create an instance of this class through <class>.newInstance(); And this is the standard way to instantinate generic type.
    I hoped line Type genericType = getClass().getGenericSuperclass(); of method returned ParameterizedType. But variable genericType cannot be casted to ParameterizedType. I don't know why. So I cannot get current generic param M and instantiate its.

  • Reference to generic type Set E should be parmeterized

    I have the following code in a class:
    1:Event theEvent = (Event) session.load(Event.class, eventId);
                2:Set<Event> eventSet;
                3:eventSet = user.getFavouriteEvents();
                4:eventSet.add(theEvent);At line 3, I get the following warning message:
    Type safety: The expresson of raw type Set is converted to Set<Event>. References to generic type Set<E> should be parameterized.
    What does this mean? What do I need to do to get past this warning.
    Thanks
    Sharma

    Found the problem. I forgot to parameterize the Set in the getFavouriteEvents() method.
    Thanks
    Sharma

  • How to create an array with Generic type?

    Hi,
    I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
    The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
    A simple implementation is just to cast the array and return, however this is not so safe.
    What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
    If I create ArrayList<T>, the class contains Object[] and not T[].
    I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
    Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
    So is there anything really wrong here, or should I simply cast the array and live with the warnings?
    Any help appreciated!

    Ok. May be you could keep information about generic type in the your class:
    public class Util {
        public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
            int size = objects.length;
            T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
            System.arraycopy(objects, 0, t, 0, size);
            return t;
    public class Sample<T> {
        Class<T> cls;
        T[] array;
        public Sample(Class<T> cls) {
            this.cls = cls;
        public void setArray(Object[] objects){
            array = Util.toTypedArray(cls, objects);
        public T[] getArray(){
            return array;
        public static void main(String[] args) {
            Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
            Sample<List> myClass = new  Sample<List>(List.class);
            myClass.setArray(objects);
            for(List elem: myClass.getArray()){
                System.out.println(elem.getClass().getName());
    }

  • Import from database an internal table with generic Type : Web Dynpro ABAP

    Hi everyone,
    i have a requirement in which i'm asked to transfer data flow between two frameworks, from WD Component to another. The problem is that i have to transfer internal tables with generic types. i used the import/ export from database approache but in that way i get an error message saying "Object references and data references not yet supported".
    Here is my code to extract a generic internal table from memory.
        DATA l_table_f4 TYPE TABLE OF REF TO data.
      FIELD-SYMBOLS: <l_table_f4> TYPE STANDARD TABLE.
      DATA lo_componentcontroller TYPE REF TO ig_componentcontroller .
      DATA: ls_indx TYPE indx.
      lo_componentcontroller =   wd_this->get_componentcontroller_ctr( ).
      lo_componentcontroller->fire_vh_search_action_evt( ).
      ASSIGN l_table_f4 TO <l_table_f4>.
    *-- Import table for Help F4
      IMPORT l_table_f4 TO <l_table_f4> FROM DATABASE indx(v1) TO ls_indx ID 'table_help_f4_ID'.
    The error message is desplayed when last instruction is executed " IMPORT l_table_f4...".
    I saw another post facing the same problem but never solved "Generic Type for import Database".
    Please can anyone help ?
    Thanks & Kind regards.

    hi KIan,
    go:
    general type
    TYPE : BEGIN OF ty_itab,
               field1 TYPE ztab-field1,
               field2 TYPE ztab-field2,
    *your own fields here:
               field TYPE i,
               field(30) TYPE c,
               END OF ty_itab.
    work area
    DATA : gw_itab TYPE ty_itab.
    internal table
    DATA : gt_itab TYPE TABLE OF ty_itab.
    hope this helps
    ec

  • 'ResourceDictionary' root element is a generic type and requires a x:Class attribute to support the x:TypeArguments attribute sp

    Error : 'ResourceDictionary' root element is a generic type and requires a x:Class attribute to support the x:TypeArguments attribute specified on the root element tag.
    Hi,
    I get this error when i include some namespaces in my ResourceDictionary to specify a Style for a custom control.
    Can anyone help me?
    Thx
    Stardusty

    Hi,
    That's the whole point. I don't want to use x:TypeArguments on a ResourceDictionary but the compiler says it needs it.
    And i don't know why.
    This code give no error:
    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespaceystem;assembly=mscorlib">  
    </ResourceDictionary>
    And by adding 3 namespaces it gives that weard error:
    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:MyTime.View.Controls"
    xmlns:converters="clr-namespace:MyTime.View.Converters"
    xmlns:validationrules="clr-namespace:MyTime.View.ValidationRules"
    xmlns:sys="clr-namespaceystem;assembly=mscorlib">  
    </ResourceDictionary>

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • New instance of a generic type?

    Hello!
    I'm quite new to writing generics and I have this (possibly lame) question: how can I create a new instance of a generic type?
    Let's say that inside a class MyClass<T> I have a method with following interface, whose only purpose would be to return new instance of the generic type T: public T getInstance(); Inside this method, I tried the obvious way of getting that instance, that is return new T(); and I also understood why that cannot be done.
    However, Googling didn't really reveal any other ways of doing this, so I'm a little stuck. Could anybody please show me the light here?

    triceo wrote:
    However, Googling didn't really reveal any other ways of doing this.Because there aren't any.
    triceo wrote:
    Could anybody please show me the light here?Search this forum. I doubt you'd have to go back more than a few hours to find the last time this question was asked.

Maybe you are looking for