script

Get script engine by name

With this example we are going to demonstrate how to get the ScriptEngine by name. The ScriptEngine interface is the fundamental interface whose methods must be fully functional in every implementation of this specification. These methods provide basic scripting functionality. Applications written to this simple interface are expected to work with minimal modifications in every implementation. It includes methods that execute scripts, and ones that set and get values. In short, to get the ScriptEngine by name you should:

  • 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 getEngineByName(String shortName) API method to look up and create a ScriptEngine for a given name.
  • Then you can use the eval(String script) method to execute a script.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
 
public class GetScriptEngineByName {
    public static void main(String[] args) {

  ScriptEngineManager manager = new ScriptEngineManager();
 

  // Create an instance of script engine using the engine name. In this example we use JavaScript

  ScriptEngine engine = manager.getEngineByName("JavaScript");
 

  try {


engine.eval("print('Hello JavaCodeGeeks Fellows');");

  } catch (ScriptException e) {


e.printStackTrace();

  }
    }
}

Output:

Hello JavaCodeGeeks Fellows

 
This was an example of how to get the ScriptEngine by name.

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