bsh.commands.eval.bsh Maven / Gradle / Ivy
/**
Evaluate the string in the current interpreter (see source()).
Returns the result of the evaluation or null.
Evaluate a string as if it were written directly in the current scope,
with side effects in the current scope.
e.g.
a=5;
eval("b=a*2");
print(b); // 10
eval() acts just like invoked text except that any exceptions generated
by the code are captured in a bsh.EvalError. This includes ParseException
for syntactic errors and TargetError for exceptions thrown by the evaluated
code.
e.g.
try {
eval("foo>>><>M>JK$LJLK$");
} catch ( EvalError e ) {
// ParseException caught here
}
try {
eval("(Integer)true"); // illegal cast
} catch ( EvalError e ) {
// TargetException caught here
print( e.getTarget() ) // prints ClassCastException
}
If you want eval() to throw target exceptions directly, without wrapping
them, you can simply redefine own eval like so:
myEval( String expression ) {
try {
return eval( expression );
} catch ( TargetError e ) {
throw e.getTarget();
}
}
Here is a cute example of how to use eval to implement a dynamic cast.
i.e. to cast a script to an arbitrary type by name at run-time where the
type is not known when you are writing the script. In this case the type
is in the variable interfaceType.
reference = eval( "("+interfaceType+")this" );
Returns the value of the expression.
Throws bsh.EvalError on error
@return the value of the expression.
@throws bsh.EvalError on error
*/
bsh.help.eval = "usage: eval( String expression )";
Object eval( String expression ) {
return this.interpreter.eval( expression, this.caller.namespace );
}