Java 显示方法参数类型的所有数组元素
我想获取数组中包含方法参数类型的所有元素(使用Java.reflect动态获取) 如果方法中有2个参数,则代码如下:Java 显示方法参数类型的所有数组元素,java,dynamic,reflection,Java,Dynamic,Reflection,我想获取数组中包含方法参数类型的所有元素(使用Java.reflect动态获取) 如果方法中有2个参数,则代码如下: Method testMethod = c.getMethod(method.getName(), new Class[] {int.class, String.class}); 但是它应该是动态的,所以我使用:method.getTypeParameters(),它返回所有参数类型的数组 然后当我写的时候: Method testMethod = c.getMethod(me
Method testMethod = c.getMethod(method.getName(), new Class[] {int.class, String.class});
但是它应该是动态的,所以我使用:method.getTypeParameters()
,它返回所有参数类型的数组
然后当我写的时候:
Method testMethod = c.getMethod(method.getName(), new Class[] {method.getParameterTypes});
但它告诉我:类型不匹配:无法从类[]转换到类
我明白我必须循环参数,因为我有:
method.getParameterTypes[0] // gives "int"
及
那么我如何才能做到这一点呢?可能是一个循环?你知道这件事吗?多谢各位
应该是
Method testMethod = c.getMethod(
method.getName(), method.getParameterTypes());
第一个问题是缺少getParameterTypes
末尾的()
。Java在调用方法时需要显式括号
第二个问题是,您试图将getParameterTypes
,一个Class[]
的结果放入Class[]
中。Class[]
只能包含单个类,而不是数组,因此只需使用getParameterTypes()
返回的数组即可
我不清楚你为什么要这么做。您可以从接口获取
方法
,并将其应用于该接口的实例,而无需在实例的具体类上查找该方法。抽象类也是如此。您不需要使用一个方法签名来获得另一个方法,除非继承图中存在漏洞或某种奇怪的对应静态方法约定。这两者都可能是重构的机会
代码库中的反射越少,人们就越容易学习,从bug Finder和其他分析工具中获得的收益就越多,不完整的类路径问题就越少。如果想查看类型,请使用Arrays.toString(method.getParameterTypeas())
。如果要迭代并使用它们,请使用循环:
for (Class<?> type : method.getParameterTypeas()) {
// use the type
}
for(类类型:method.getParameterTypeas()){
//使用类型
}
您使用的是getParameterTypes()
还是getTypeParameters()
(示例中两者都有)?有一个很大的区别…我使用getParameterTypes
谢谢,它很有效。这个过程是一个外部应用程序向我发送方法名、参数和ID,我需要从目录中加载一个具有此ID的jar。jar包含webservice客户端的代理类,以最终使用webservice并使用其pamaters执行该方法。我知道这很令人困惑。。
Method testMethod = c.getMethod(
method.getName(), method.getParameterTypes());
for (Class<?> type : method.getParameterTypeas()) {
// use the type
}