【发布时间】:2011-12-18 09:27:58
【问题描述】:
当我使用 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 方法来解决此问题,我将不胜感激。
谢谢!
【问题讨论】:
-
你的 Exec 方法应该命名为 exec,而不是 Clas.forName("java.lang.string"),你可以只做 String.class :更短更安全。
-
我为什么要把它命名为“exec”?由于命名约定,或者您指的是其他任何东西。感谢您的提示,它使我的代码更清晰。
-
是的,尊重 Java 命名约定。在 Java 中,方法总是以小写字母开头。
标签: java reflection methods parameter-passing invoke