Home » Core Java » script » Import package in script

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of