How do I import Java package in script?

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() {
        StringBuilder sb = new StringBuilder();
        sb.append("importPackage(java.util);");
        sb.append("");
        sb.append("var today = new Date();");
        sb.append("println('Today is ' + today);");
        return sb.toString();
    }
}

This program prints the following line:

Today is Fri Sep 11 2009 17:03:02 GMT+0800 (CST)

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply