Gre*_*reg 1 java generics reflection
鉴于此方法:
public final void foo (List<MyClass> bar){ .. }
Run Code Online (Sandbox Code Playgroud)
我希望能够反思地调用这个方法.为了使getMethod工作,我必须将其更改为:
public final void foo (List bar){ .. }
Run Code Online (Sandbox Code Playgroud)
出于显而易见的原因,这似乎并不正确,但getMethod的输入组合似乎不起作用.我在谷歌搜索高低都无济于事.有什么建议?
干杯谢谢!
import java.util.*;
import java.lang.reflect.*;
public class Test {
public final void foo (List<String> bar){
for(String x : bar)
System.out.println(x);
}
public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Test x = new Test();
List<String> y = new ArrayList<String>(); y.add("asd"); y.add("bsd");
x.getClass().getMethod("foo",List.class).invoke(x,y);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以只使用getMethod("foo",List.class)和使用,List.class因为通用信息List<String>仅在编译时使用.在运行时,方法签名看起来像
public final void foo (List bar)
Run Code Online (Sandbox Code Playgroud)
因为在编译时类型擦除摆脱了通用信息.
| 归档时间: |
|
| 查看次数: |
1537 次 |
| 最近记录: |