当我使用 Java 反射 API 调用一个接受可变数量参数的方法时,我在尝试解决这种情况时遇到了问题。每次我尝试这样做时,我都会收到“NoSuchMethodException”。
我要调用的方法声明:
public void AddShow(String movieName, String cinemaName, String... days) {
}
以及执行调用的方法的代码:
public void Exec(String command){
try {
String[] words = command.split(" ");
String commandName = words[0];
Class<? extends UserInterface> thisClass = (Class<? extends UserInterface>)getClass();
Class<String>[] par = new Class[words.length-1];
String[] params = new String[words.length-1];
for(int i = 1; i< words.length; i++){
params[i-1] = words[i];
try {
par[i-1] = (Class<String>) Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
System.out.println("If this shows up, something is siriously wrong... Waht have you done?!");
}
}
Method method;
if(par.length != 0) {
method = thisClass.getMethod(commandName, par);
method.invoke(new UserInterface(CinemaDb), (Object[])params);
} else {
method = thisClass.getMethod(commandName);
method.invoke(new UserInterface(CinemaDb));
}
} catch (SecurityException e) {
System.out.println("Security error, sry again.");
} catch (NoSuchMethodException e) {
System.out.println("Wrong command, try again (check the parameters)!");
} catch (IllegalAccessException e) {
System.out.println("You don't have access rights, try again.");
} catch (IllegalArgumentException e) {
System.out.println("Wrong arguments, try again.");
} catch (InvocationTargetException e) {
System.out.println("Invocation error, try again.");
}
}
如果您知道如何更改我的 Exec 方法来解决这个问题,我将不胜感激。
谢谢!
最佳答案
Java 中的可变参数是通过数组实现的,因此参数为 String.class、String.class 和 String[].class
。
关于Java 反射 API 和调用具有可变数量参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7948249/