Run Scripting Language (JavaScript, Python, Groovy, Ruby) in Java


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);
    }
}

Hello Java from 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.

-




Have Questions? Post them here!