script

Import package in script

In this example we shall show you how to import a package in script. We are using the ScriptEngine interface, that provides methods for basic scripting functionality. To import a package in script one should perform the following steps:

  • Create a StringBuilder to build the script. Append to it all the commands to be executed, along with the import package command. Get the String representation of the StringBuilder, to be used as the script.
  • Create a new ScriptEngineManager. The ScriptEngineManager implements a discovery and instantiation mechanism for ScriptEngine classes and also maintains a collection of key/value pairs storing state shared by all engines created by the Manager.
  • Use the getEngineByExtension(String extension) API method to look up and create a ScriptEngine for the js extension.
  • Use the eval(String script) method to execute the script,

as described in the code snippet below.  

package com.javacodegeeks.snippets.core;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
 
public class ImportPackage {
	
    public static void main(String[] args) {
    	
    	// Create script engine manager and set js engine

  ScriptEngineManager manager = new ScriptEngineManager();

  ScriptEngine engine = manager.getEngineByExtension("js");
 

  try {


engine.eval(getScript());

  } catch (ScriptException e) {


e.printStackTrace();

  }
    }
 
    // Get script method that includes the import of java.util package
    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();
    }
}

Output:

Today is Sat Aug 11 2012 20:06:08 GMT+0300 (EEST)

  
This was an example of how to import a package with a script in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button