As you may know Java is not a scripting language, but it is possible to execute scripts written in scripting languages like JavaScript or Groovy using the Nashorn Scripting Engine.
Let us see a very basic "hello world" example:
package org.code2care.java.examples;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
String javaScript = "var message = 'Hello Java from JavaScript!'; print(message);";
engine.eval(javaScript);
}
}
The Java Scripting API is a built-in feature of Java that allows you to execute scripts written in various languages, including JavaScript, Groovy, Ruby, and Python.
ScriptEngine is the class that you will create an instance of passing in the scripting language that you want to use, and make use of the eval() method to execute the script.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!