ArrayList reflection [duplicate]

2019-07-28 17:04发布

问题:

Possible Duplicate:
How do I find out what type each object is in a ArrayList<Object>?
Knowing type of generic in Java

How can I retrieve the Type Foo from my ArrayList using the reflection in Java?

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

回答1:

You can't 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 inspected, but not local variables or values

These produce the same result.

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

You cannot obtain a generic type for

List myList = new ArrayList<Foo>();