![](/img/trans.png)
[英]Java Reflection ArrayList.class.getMethod(“get”) returns NoSuchMethodException
[英]Java getMethod() results in NoSuchMethodException error
我试图在用户输入字符串命令时使用反射来启动适当的方法。 例如,如果用户在终端中输入“go”,则Player类的go()方法将由Command类的process()方法调用。
但是,我无法使我的代码工作,并且我得到NoSuchMethodException错误,我不知道如何修复。 问题根源的行是Command类的一半(在底部复制完整的类):
try {
Method method = pClass.getMethod(commandWord);
method.invoke(player, this);
}
catch (NoSuchMethodException err1) {
System.out.println("No such method");
}
有人可以指导我吗? 我提前谢谢你。
LC
命令类:
import java.util.ArrayList;
import java.lang.reflect.*;
public class Command
{
private String commandWord;
private String secondWord;
public Command(String firstWord, String secondWord)
{
commandWord = firstWord;
this.secondWord = secondWord;
}
public boolean process(Player player)
{
ArrayList<String> validCommands = new ArrayList<String>();
String methodName;
int index;
Class pClass = player.getClass();
Method[] methods = pClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (Modifier.isPublic(methods[i].getModifiers())) {
validCommands.add(methods[i].getName());
}
}
boolean wantToQuit = false;
if(commandWord == null) {
System.out.println("I don't know what you mean...");
return false;
}
if (commandWord.equals("help")) {
System.out.println("You are lost. You are alone. You wander");
System.out.println("around at the university.");
System.out.println();
System.out.println("Your command words are:");
for(String command: validCommands) {
System.out.print(command + " ");
}
System.out.println();
}
else if (commandWord.equals("quit")) {
wantToQuit = quit();
}
//THIS IS WHERE I GET THE ERROR
try {
Method method = pClass.getMethod(commandWord);
method.invoke(player, this);
}
catch (NoSuchMethodException err1) {
System.out.println("No such method");
}
catch (IllegalAccessException err2) {
System.out.println("Illegal access");
}
catch (InvocationTargetException err3) {
System.out.println("Illegal access");
}
return wantToQuit;
}
[...] //some methods omitted
}
玩家类:
public class Player
{
private String name;
private Room currentRoom;
private ArrayList<Item> items;
Player (String name, Room startingRoom)
{
this.name = name;
items = new ArrayList<Item>();
this.currentRoom = startingRoom;
printWelcome();
}
public void engage()
{
[...]
}
public void trade(Command command)
{
[...] }
public void goRoom(Command command)
{
[...] }
public void search(Command command)
{
[...] }
public void takeItem(Command command)
{
[...] }
public void dropItem(Command command)
{
[...] }
public void lock(Command command)
{
[...] }
public void unlock(Command command)
{
[...]
}
}
尝试这个。
pClass.getMethod(commandWord, Command.class)
在我看来问题是你正在寻找没有的方法
参数虽然这些方法似乎都有一个Command
类型的参数。
有关详细信息,请参阅此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.