【发布时间】:2018-11-18 12:01:08
【问题描述】:
我正在使用 Java 反射进行测试,并尝试根据参数类型将重载方法应用于参数..
但是,即使我尝试获取的方法是公开的,我也有 NoSuchMethodException。在我使用 getDeclaredMethod 时仍然出现此异常。
这是主程序
public class Test {
public static void main(Object... inputs){
InputManipulation test = new InputManipulation();
for (Object input: inputs){
Class ownerClass = test.getClass();
Class inputClass = input.getClass();
Method method = ownerClass.getDeclaredMethod("add", inputClass);
method.invoke(test, "Testing reflection");
}
}
}
这是自定义的 InputManipulation 类
public class InputManipulation {
Integer total;
public InputManipulation(){this.total = 0;}
public void add(Integer num){this.total += num;}
public void add(String str){System.out.println(str);}
}
提前致谢!
我现在改了Test类如下..但问题依旧存在。
public class Test {
public static void main(String[] args){
Test testExample = new Test();
testExample.testMethod("String1", 1, "String2");
}
public void testMethod(Object... inputs){
InputManipulation test = new InputManipulation();
for (Object input: inputs){
Class ownerClass = test.getClass();
Class inputClass = input.getClass();
Method method = ownerClass.getDeclaredMethod("add", inputClass);
method.invoke(test, "Testing reflection");
}
}
}
我还尝试按照另一篇文章的建议将 inputClass 放入 Class 数组中,但没有帮助..
【问题讨论】:
-
如何启动这个应用程序?
-
您的
main()方法没有Java 正确的main()方法签名,请看这里protechtraining.com/content/… -
你的代码不可编译,你怎么会出现异常?!
-
OP 其实讲的是编译器错误:
Unhandled exception type NoSuchMethodException -
@CherylYang 看看我对修复的第一条评论。实际上,如果你有一个合适的 IDE,它应该会建议你如何修复它
标签: java get-method