[英]Calling a method from user input in JAVA
我正在尋找一種方法來調用我的類中的任何給定方法,而無需執行整個try-catch
語句。
例子:
public void Worker(String handle) throws Exception
{
if(PROTOCOL.contains(handle))
{
System.out.println("good");
Worker.handle;
}
else {
throw new Exception("Don't understand <" + handle + ">");
}
}
PROTOCOL
是允許的命令列表。
我知道我可以說if(input = ....){do....}
但我希望能夠做到以上幾點; 用輸入值調用我的類。
這可能嗎?
根據您的命令的外觀,您可以使用Map<String, Command>
,然后您可以像這樣使用:
Map<String, Command> PROTOCOL = ... //you build that map somehow
Command c = PROTOCOL.get(handle);
if( c != null ) {
System.out.println("good");
c.execute();
} else {
throw new Exception("Don't understand <" + handle + ">");
}
Command
可以是一個類或函數接口:
interface Command {
void execute();
}
用作類接口
class MyCommand implements Command {
//this can have private data
void execute() {
//do whatever is needed
}
}
PROTOCOL.put("mycommand", new MyCommand(/*you could pass parameters here*/));
好處:
String getName()
。AddCommand(1)
和AddCommand(-1)
) .PROTOCOL
。 這樣你甚至可以通過一些插件機制添加命令。用作函數接口(例如通過 lambdas)
PROTOCOL.put("mycommand", () -> {
//do whatever is needed
});
好處:
如果您不想使用 try-catch(自己處理異常),則在 throws 關鍵字之后的調用方法上聲明這些異常。
https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html
基本上,您將異常處理委托給方法的調用者。
這是一個簡單的工作示例,展示了您可以使用反射做的一些事情。
注意:我決定將可用的方法存儲在一個列表中,但這可以很容易地修改為使用預定義的字符串列表。 我還從工作方法中拋出了一個未經檢查的 IllegalArgumentException。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Worker {
public void method1() {
System.out.println("method1 called");
}
public void method2() {
System.out.println("method2 called");
}
public void worker(String handle) throws IllegalArgumentException {
Class<? extends Worker> clazz = this.getClass();
List<Method> methods = Arrays.asList(clazz.getMethods());
if (methods.stream().map(m -> m.getName()).collect(Collectors.toList()).contains(handle)) {
try {
Method method = clazz.getDeclaredMethod(handle);
method.invoke(this);
} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
e.printStackTrace();
}
} else {
throw new IllegalArgumentException("Don't understand <" + handle + ">");
}
}
public static void main(String[] args) {
new Worker().worker("method1");
new Worker().worker("method2");
new Worker().worker("method3");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.