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)

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!