Luc*_*uca 1 java reflection arraylist
如何Foo从我ArrayList使用Java中的反射中检索Type ?
ArrayList<Foo> myList = new ArrayList<Foo>();
Run Code Online (Sandbox Code Playgroud)
您无法从值中获取此类型,但您可以从字段信息中获取此类型.
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
版画
interface Main$Foo
Run Code Online (Sandbox Code Playgroud)
可以检查字段,方法参数,返回类型和扩展类/接口,但不能检查局部变量或值
这些产生了相同的结果.
List<Foo> myList = new ArrayList();
List<Foo> myList = (List) new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)
您无法获取通用类型
List myList = new ArrayList<Foo>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5582 次 |
| 最近记录: |