嗨,我最近遇到的每个人都遇到了-> 在这里可以找到源。,发现它使用.eval()方法将字符串计算为算术操作,查看我找到的符号对象的这个方法:
/**
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();
}此方法调用编译器编译对象的.compileSimple:
Function compileSimple(Symbols symbols, String expression) throws SyntaxException {
rpn.setConsumer(simpleCodeGen.setSymbols(symbols));
lexer.scan(expression, rpn);
return simpleCodeGen.getFun();
}它返回一个函数对象,然后调用对此函数对象的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必须返回双重类型,并且实现抛出具有此实现的ArityException:
public class ArityException extends RuntimeException {
public ArityException(String mes) {
super(mes);
}
public ArityException(int nArgs) {
this("Didn't expect " + nArgs + " arguments");
}
}但是当抛出ArityException时,它会调用RuntimeException的超级()构造函数,这是一个异常,不像它应该的那样双返回,也许我弄乱了一些段落,但我不理解在Function.eval()实现中最后抛出0的新ArityException。
那么它到底是如何工作的呢?
发布于 2014-06-18 15:45:28
你错过了simpleCodeGen的声明
private final SimpleCodeGen simpleCodeGen = new SimpleCodeGen(exception);这意味着compileSimple(...)实际上返回了一个CompiledFunction,它扩展了ContextFunction和类似的Function。
CompiledFunction getFun() {
return new CompiledFunction(0, code.toArray(), consts.getRe(), consts.getIm(), funcs.toArray());
}实际上,调用的是ContextFunction中的ContextFunction函数。它有一个真正的实现。
在没有IDE的情况下进行代码分析,仅仅观察代码可能是很棘手的。使用调试器和逐步通过将很容易地显示程序流。
https://stackoverflow.com/questions/24286965
复制相似问题