script

Evaluate a simple script

This is an example of how to evaluate a simple script in Java. We are using the ScriptEngine interface, that provides methods for 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. Evaluating a script implies that 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 getEngineByExtension(String extension) method to look up and create a ScriptEngine for a given extension.
  • Use the eval(String script) method to execute a script.

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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.javacodegeeks.snippets.core;
 
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
  
public class EvaluateScriptExample {
    public static void main(String[] args) {
 
   
        // Create script engine instance and get extension
 
  ScriptEngineManager manager = new ScriptEngineManager();
 
  ScriptEngine js = manager.getEngineByExtension("js");
  
 
  try {
 
 
// Evaluate script
 
 
js.eval("print('Hello JavaCodeGeeks Fellow')");
 
  } catch (ScriptException e) {
 
 
e.printStackTrace();
 
  }
    }
}

Output:

Hello JavaCodeGeeks Fellow

  
This was an example of how to evaluate a simple script in Java.

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 ....
I agree to the Terms and Privacy Policy

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