我正在尝试使用 Java 反射,我有两种不同的方法可以调用。其中一个有一个字符串参数,第二个有两个字符串参数。我已经设法使第一个工作正常,但仍在为第二个工作而苦苦挣扎。我已经检查了对其他两个问题( Java reflection: getMethod(String method, Object[].class) not working 和 How to invoke method with variable arguments in java using reflection? )的引用,但不幸的是没有运气。我不断收到以下异常:
java.lang.NoSuchMethodException: controllers.InventoryController.combineItems([Ljava.lang.String;)
at java.lang.Class.getMethod(Unknown Source)
这是我的代码工作部分:
Class[] paramString = new Class[1];
paramString[0] = String.class;
try {
Class cls = this.getClass();
Method method = cls.getDeclaredMethod(commandParts[0], paramString);
method.invoke(this, new String(commandParts[1]));
} catch (Exception ex) {
System.out.println("Doesn't work");
ex.printStackTrace();
}
现在这是我无法开始工作的部分:
Class[] paramString = new Class[2];
paramString[0] = String[].class;
try {
Class cls = this.getClass();
Method method = cls.getMethod(commandParts[0], paramString[0]);
method.invoke(this, new String[]{commandParts[1], commandParts[2]});
} catch (Exception ex) {
System.out.println("Doesn't work");
ex.printStackTrace();
}
传递多个参数的正确方法是什么?
最佳答案
错误是因为
Method method = cls.getMethod(commandParts[0], paramString[0]);
这表示返回方法名称“commandParts[0]”只有一个类型为“paramString[0]”的参数 用
改变这个Method method = cls.getMethod(commandParts[0], String.class, String.class);
关于Java反射多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17967585/