【发布时间】:2014-06-18 13:33:03
【问题描述】:
大家好,我最近遇到了 Arity 库 -> source can be found here 并发现它使用 .eval() 方法将字符串评估为算术运算,查看源代码我发现了 Symbols 对象的这个方法:
/**
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();
}
该方法调用Compiler编译对象的.compileSimple:
Function compileSimple(Symbols symbols, String expression) throws SyntaxException {
rpn.setConsumer(simpleCodeGen.setSymbols(symbols));
lexer.scan(expression, rpn);
return simpleCodeGen.getFun();
}
它返回一个 Function 对象,然后对其调用 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,也许我有一些段落,但我不明白最后一个 throw new Function.eval() 实现中的 0 的 ArityException。
那么它到底是如何工作的呢?
【问题讨论】: