我正在寻找一种方法来调用我的类中的任何给定方法,而无需执行整个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
基本上,您将异常处理委派给方法的调用者。
这是一个简单的工作示例,显示了使用reflection可以执行的一些操作。
注意:我决定在列表中存储可用的方法,但是可以很容易地修改它以使用预定义的字符串列表。我还从worker方法中抛出了一个未经检查的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");
}
}