Reflection ArrayList

Possible duplicate:
How do I know what type of each object is in an ArrayList <Object>? Know the generic type in Java

How can I get Type Foofrom mine ArrayListusing reflection in Java?

ArrayList<Foo> myList = new ArrayList<Foo>();
+1
source share
1 answer

You cannot get this type from the value, but you can get it from the field information.

public class Main {
    interface Foo { }
    class A {
        List<Foo> myList = new ArrayList<Foo>();
    }
    public static void main(String... args) throws NoSuchFieldException {
        ParameterizedType myListType = ((ParameterizedType) 
                                A.class.getDeclaredField("myList").getGenericType());
        System.out.println(myListType.getActualTypeArguments()[0]);
    }
}

prints

interface Main$Foo

Fields, method arguments, return types, and extended classes / interfaces can be checked, but not local variables or values

They give the same result.

List<Foo> myList = new ArrayList();
List<Foo> myList = (List) new ArrayList<String>();

You cannot get a generic type for

List myList = new ArrayList<Foo>();
+9
source

All Articles