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 let Date = Java.type("java.util.Date")
.
package org.kodejava.script;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.function.Predicate;
public class ImportPackageExample {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("polyglot.js.allowHostAccess", true);
bindings.put("polyglot.js.allowHostClassLookup", (Predicate<String>) s -> true);
try {
engine.eval(getScript());
} catch (ScriptException e) {
e.printStackTrace();
}
}
private static String getScript() {
return """
let Date = Java.type("java.util.Date");
let today = new Date();
print(`Today is ${today.toString()}`);
print(`today is ${today.getClass().getName()}`);
""";
}
}
This program prints the following line:
Today is Sun Oct 10 15:15:13 CST 2021
today is java.util.Date
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js</artifactId>
<version>22.3.2</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js-scriptengine</artifactId>
<version>22.3.2</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024