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>();
source
share