如何使用 Java 中的反射Foo
从我的类型中检索类型?ArrayList
ArrayList<Foo> myList = new ArrayList<Foo>();
如何使用 Java 中的反射Foo
从我的类型中检索类型?ArrayList
ArrayList<Foo> myList = new ArrayList<Foo>();
您无法从值中获取此类型,但可以从字段信息中获取。
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]);
}
}
印刷
interface Main$Foo
可以检查字段、方法参数、返回类型和扩展类/接口,但不能检查局部变量或值
这些产生相同的结果。
List<Foo> myList = new ArrayList();
List<Foo> myList = (List) new ArrayList<String>();
您无法获得泛型类型
List myList = new ArrayList<Foo>();