ArrayList reflection [duplicate]

2019-07-28 16:30发布

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条回答
混吃等死
2楼-- · 2019-07-28 16:56

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>();
查看更多
登录 后发表回答