如何使用 Java 中的字符串为变量赋值(不是求值)
How to assign value to a variable using string in Java (not evaluation)
假设我有,
- 一个字符串
String foo = "a+b"
- 变量
a
和b
、Integer a = 2
Integer b = 3
我想以某种方式分配新的整数,c
应该使用字符串 foo
.
从 a
和 b
计算得出
eval 不起作用,因为它只能计算绝对值而不是变量值。
您可以使用 JEP Java 表达式解析器库(或其他表达式解析器)。
例如:
String foo = "a+b";
Jep jep = new Jep();
try {
jep.addVariable("a", a);
jep.addVariable("b", b);
jep.parse(foo);
Object result = jep.evaluate();
System.out.println("foo = " + result);
} catch (JepException e) {
System.out.println("An error occurred: " + e.getMessage());
}
编辑:
事实证明,JEP(此处:http://www.singularsys.com/jep/)是许可软件,因此您必须付费,但还有另一种选择。
还有许多其他类似的库,包括 JEPLite (http://jeplite.sourceforge.net/index.html),它似乎(据我所知)是免费版本并且应该兼容。
假设我有,
- 一个字符串
String foo = "a+b"
- 变量
a
和b
、Integer a = 2
Integer b = 3
我想以某种方式分配新的整数,c
应该使用字符串 foo
.
a
和 b
计算得出
eval 不起作用,因为它只能计算绝对值而不是变量值。
您可以使用 JEP Java 表达式解析器库(或其他表达式解析器)。
例如:
String foo = "a+b";
Jep jep = new Jep();
try {
jep.addVariable("a", a);
jep.addVariable("b", b);
jep.parse(foo);
Object result = jep.evaluate();
System.out.println("foo = " + result);
} catch (JepException e) {
System.out.println("An error occurred: " + e.getMessage());
}
编辑:
事实证明,JEP(此处:http://www.singularsys.com/jep/)是许可软件,因此您必须付费,但还有另一种选择。
还有许多其他类似的库,包括 JEPLite (http://jeplite.sourceforge.net/index.html),它似乎(据我所知)是免费版本并且应该兼容。