How To Import Java Package Inside JavaScript using ScriptEngine

This example show how to import Java package inside JavaScript. We can import the Java package and use the classes inside the scripts. In this example, I have imported the java.util package and use java.util.Date class to print today’s date. Lets look at the example.



import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

 * Java ScriptEngine Import Package Example
 * @author Krishna
public class JavaScriptEngineImportPackageExample {
	public static void main(String[] args) throws ScriptException,
			FileNotFoundException, NoSuchMethodException {

		// Create ScriptEngineManager
		ScriptEngineManager engineManager = new ScriptEngineManager();

		// Create ScriptEngine
		ScriptEngine engine = engineManager.getEngineByName("ECMAScript");

		//Import package statement in string buffer
		StringBuffer buffer = new StringBuffer();
		buffer.append("var todayDate = new Date();");
		buffer.append("println('Today Date Is ' + todayDate);");

		//Execute the script



Today Date Is Tue Apr 22 2014 15:04:46 GMT+0530 (IST)



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.