Here you can see how to import a Java class so that you can use the class, creates an instance of it in the scripting environment. We want to print out the current date on the console. For this we need to import the Date
class that’s packaged under the java.util
package.
In the script we can import the java.util
package using the following script importPackage(java.util)
.
package org.kodejava.example.script;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class ImportPackageExample {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
try {
engine.eval(getScript());
} catch (ScriptException e) {
e.printStackTrace();
}
}
private static String getScript() {
return "importPackage(java.util);" +
"var today = new Date();" +
"println('Today is ' + today);";
}
}
This program prints the following line:
Today is Fri Dec 21 2018 22:57:36 GMT+0800 (WITA)
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020