Java Reference
In-Depth Information
Return Value of the eval( ) Method
The
eval()
method of the
ScriptEngine
returns an
Object
, which is the last value in the
script. It returns
null
if there is no last value in the script. It is error-prone, and confusing
at the same time, to depend on the last value in a script. The following snippet of code
shows some examples of using the return value of the
eval()
method for Nashorn.
The comments in the code indicate the returned value from the
eval()
method:
Object result = null;
// Assigns 3 to result because the last expression 1 + 2 evaluates to 3
result = engine.eval("1 + 2;");
// Assigns 7 to result because the last expression 3 + 4 evaluates to 7
result = engine.eval("1 + 2; 3 + 4;");
// Assigns 6 to result because the last statement v = 6 evaluates to 6
result = engine.eval("1 + 2; 3 + 4; var v = 5; v = 6;");
// Assigns 7 to result. The last statement "var v = 5" is a
// declaration and it does not evaluate to a value. So, the last
// evaluated value is 3 + 4 (=7).
result = engine.eval("1 + 2; 3 + 4; var v = 5;");
// Assigns null to result because the print() function returns undefined
// that is translated to null in Java.
result = engine.eval("print(1 + 2)");
It is better not to depend on the returned value from the
eval()
method. You should
pass a Java object to the script as a parameter and let the script store the returned value
of the script in that object. After the
eval()
method is executed, you can query that Java
object for the returned value. Listing 3-5 contains the code for a
Result
class that wraps
an integer. You will pass an object of the
Result
class to the script that will store the
returned value in it. After the script finishes, you can read the integer value stored in the
Result object in your Java code. The
Result
needs to be declared public so it is accessible
to the script engine. The program in Listing 3-6 shows how to pass a
Result
object to
a script that populates the
Result
object with a value. The program contains a
throws
clause in the
main()
method's declaration to keep the code short.
Search WWH ::
Custom Search