📜  Java 8-Nashorn JavaScript(1)

📅  最后修改于: 2023-12-03 14:42:12.668000             🧑  作者: Mango

Java 8-Nashorn JavaScript

Java 8 introduced a new feature called Nashorn, a lightweight JavaScript engine that is integrated with Java. With Nashorn, developers can run JavaScript on the JVM (Java Virtual Machine) and seamlessly integrate it with Java code.

Benefits
High Performance

Nashorn has a performance boost of over 5 times that of the previous script engine, Rhino.

Interoperability

Nashorn allows seamless integration between Java code and JavaScript code. Java objects can be accessed from JavaScript and vice versa.

Easy to use

Nashorn provides an easy-to-use command-line interface for testing and debugging scripts.

Example Code
Java code calling JavaScript function
import javax.script.*;

public class NashornExample {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager engineManager = new ScriptEngineManager();
        ScriptEngine engine = engineManager.getEngineByName("nashorn");

        engine.eval("function greet(name){ return 'Hello ' + name; }");
        Invocable invocable = (Invocable) engine;
        String result = (String) invocable.invokeFunction("greet", "John");
        System.out.println(result); // Output: Hello John
    }
}
JavaScript code calling Java function
var Runnable = Java.type('java.lang.Runnable');
var runnable = new Runnable() {
    run: function() {
        print('Hello from Java');
    }
};
runnable.run();
Conclusion

Nashorn is a powerful tool for developers who want to integrate JavaScript with their Java codebase. Its high performance, easy-to-use interface, and interoperability with Java make it a valuable addition to the Java developer's toolkit.