Java Reference
In-Depth Information
// Print the class name and the value of the
// variable year
System.out.println("year's class:" + year.
getClass().getName());
System.out.println("year's value:" + year);
}
catch (ScriptException e) {
e.printStackTrace();
}
}
}
year's class:java.lang.Integer
year's value:1969
The program declares a global variable year in the script and assigns it a value of
1969 as shown:
String script = "var num = 1969";
When the script is executed, the engine adds the year variable to its state. In Java
code, the get() method of the engine is used to retrieve the value of the year variable as
shown:
Object year = engine.get("year");
When the year variable was declared in the script, you did not specify it data type.
The conversion of a script variable value to an appropriate Java object is automatically
performed. If you run the program in Java 7, your output will show java.lang.Double as
the class name and 1960.0 as the value for the year variable. This is because Java 7 uses
Rhino script engine that interprets 1969 as a Double whereas Java 8 uses Nashorn script
engine that interprets it as an Integer .
Summary
A ScriptEngine can execute a script in a String and a Reader . The eval() method of
the ScriptEngine is used execute the script. The method is overloaded and it has six
versions. It lets you pass the script as the first argument and the parameters to the engine
in the second.
The eval() method of the ScriptEngine is used execute the script. You can pass
parameters to the script and read values from scripts back to the Java program. There
are different ways to pass parameters from the Java program to scripts. You can use the
put(String key, Object value) method of the ScriptEngine to pass a parameter with
the name key to the script. You can use the get(String key) method to get the global
variables stored in the script with the name key .
 
Search WWH ::




Custom Search