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.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap