我可以将String映射到Java中的方法吗? [英] Can I map a String to a method in java?
问题描述
我正在用Java编写一个表达式评估器.我想要添加更多运算符的能力(我目前只有(,),+,-,*,/和^).目前,我的代码如下:
I'm writing an expression evaluator in Java. I would like the ability to add more operators (I currently have only (, ), +, -, *, /, and ^). Currently, my code looks like this:
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
...
这对我的代码有效,因为我只有几个运算符.但是,如果我要添加更多运算符,则代码将变得混乱.我正在寻找一种将运算符(由String表示)映射到方法的方法.例如,"ln"将映射到Math.log(),"^"将映射到Math.pow(),等等.
This works for my code because I have only a few operators. However, if I were to add more operators, the code would become cluttered. I am looking for a way to map an operator (represented by a String) to a method. For example, "ln" would be mapped to Math.log(), "^" would be mapped to Math.pow(), etc.
我将如何去做?如果不可行,有什么替代方法?
How would I go about doing this? If it's not feasible, what are some alternatives?
推荐答案
除非您要使用反射,否则不可能.没有反射的解决方案可能看起来像这样:
Not possible unless you want to use reflection. A solution without reflection could look like this:
public interface Operation {
int apply(int... operands);
}
public abstract class BinaryOperation implements Operation {
@Override
public int apply(int... operands) {
return apply(operands[0], operands[1]);
}
abstract int apply(int a, int b);
}
Map<String, Operation> operations = new HashMap<String, Operation>() {{
put("+", new Operation() {
@Override
public int apply(int... operands) {
return operands[0] + operands[1];
}
});
put("-", new BinaryOperation() {
@Override
public int apply(int a, int b) {
return a - b;
}
});
}};
这篇关于我可以将String映射到Java中的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!