我有一个带有字段
a
和 b
的对象。例如,我需要向 JSON 添加 object.a+10
逻辑,然后将此 JSON 传递给 Java 并对对象及其字段 a
执行操作。
我想这样写:
{
"object" : {
"a": 1,
"b": 10
},
"operand1": "object.a",
"operand2": "10",
"operation": "+"
}
或者像这样:
{
"object" : {
"a": 1,
"b": 10
},
"action": "object.a + 10",
}
可能吗?如何更好地实施?
您可以使用第一个选项,将操作转换为枚举,以便它可以处理某些操作。
不要忘记添加适当的异常处理等。
public class Calculation {
private Operand object;
private String operand1;
private String operand2;
private OperationEnum operation;
// . . .
public int calculate(){
int number1 = Integer.parseInt(operand1 );
int number2 = Integer.parseInt(operand1 );
return operation.apply(number1, number2);
}
}
public enum OperationEnum{
PLUS("+", (a, b) -> a + b),
MINUS("-", (a, b) -> a - b),
DIVIDE("/", (a, b) -> {
if (b == 0) throw new ArithmeticException("Cannot divide by zero");
return a / b;
}),
MULTIPLY("*", (a, b) -> a * b);
private final String symbol;
private final BiFunction<Integer, Integer, Integer> operation;
Operation(String symbol, BiFunction<Integer, Integer, Integer> operation) {
this.symbol = symbol;
this.operation = operation;
}
public int apply(int a, int b) {
return operation.apply(a, b);
}
// . . .
}