Java jar算术库如何计算操作字符串?
大家好,我最近遇到了Arity图书馆-> 并发现它使用.eval()方法将字符串作为算术运算求值,查看源代码,我发现Symbols对象的此方法:Java jar算术库如何计算操作字符串?,java,eval,Java,Eval,大家好,我最近遇到了Arity图书馆-> 并发现它使用.eval()方法将字符串作为算术运算求值,查看源代码,我发现Symbols对象的此方法: /** Evaluates a simple expression (such as "1+1") and returns its value. @throws SyntaxException in these cases: <ul> <li> the expression
/**
Evaluates a simple expression (such as "1+1") and returns its value.
@throws SyntaxException in these cases:
<ul>
<li> the expression is not well-formed
<li> the expression is a definition (such as "a=1+1")
<li> the expression is an implicit function (such as "x+1")
</ul>
*/
public synchronized double eval(String expression) throws SyntaxException {
return compiler.compileSimple(this, expression).eval();
}
它返回一个函数对象,然后对该对象调用eval()方法。查看Function.eval()方法时,我看到:
/**
Evaluates an arity-0 function (a function with no arguments).
@return the value of the function
*/
public double eval() {
throw new ArityException(0);
}
方法eval必须返回一个double类型,并且实现抛出一个具有此实现的ArityException:
public class ArityException extends RuntimeException {
public ArityException(String mes) {
super(mes);
}
public ArityException(int nArgs) {
this("Didn't expect " + nArgs + " arguments");
}
}
但是当抛出ArityException时,它调用RuntimeException的super()构造函数,这是一个异常,并且没有像它应该返回的那样返回double,可能我弄乱了一些段落,但是我不理解函数.eval()实现中最后一个抛出新的ArityException 0
那么它到底是如何工作的呢?您错过了
simpleCodeGen
的声明:
private final SimpleCodeGen simpleCodeGen = new SimpleCodeGen(exception);
这意味着compileSimple(…)
实际上返回一个CompiledFunction
,该函数扩展了ContextFunction
等函数
CompiledFunction getFun() {
return new CompiledFunction(0, code.toArray(), consts.getRe(), consts.getIm(), funcs.toArray());
}
实际上,调用的是ContextFunction
中的eval(…)
函数。这是一个真正的实现
在没有IDE的情况下进行代码分析,而只是观察代码可能会很棘手。使用调试器和单步执行将很容易向您展示程序流程。感谢您的解释!
CompiledFunction getFun() {
return new CompiledFunction(0, code.toArray(), consts.getRe(), consts.getIm(), funcs.toArray());
}