JavaScriptHello - SJP API Hello Example

Q

How to use the SJP (Scripting for the Java Platform) API to write a simple "Hello World!" example?

✍: FYIcenter

A

You can follow this tutorial to use the SJP (Scripting for the Java Platform) API to write a simple "Hello World!" example:

1. Create a JavaScript ScriptEngine object with an instance of ScriptEngineManager:

      ScriptEngineManager f = new ScriptEngineManager();
      ScriptEngine e = f.getEngineByName("JavaScript");

2. Call the eval() method on the ScriptEngine object to run a JavaScript code:

      e.eval("print('   Hello world!')");

Here is the entire sample program, JavaScriptHello.java, that shows you how to use the SJP (Scripting for the Java Platform) API:

// Copyright (c) 2017 FYIcenter.com
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class JavaScriptHello {
   public static void main(String[] args) throws Exception {
      ScriptEngineManager f = new ScriptEngineManager();
      ScriptEngine e = f.getEngineByName("JavaScript");

      System.out.println("\nFrom JavaScript:");
      e.eval("print('   Hello world!')");
    }
}

Compile and run it:

>\fyicenter\jdk-1.8.0\bin\javac JavaScriptHello.java

>\fyicenter\jdk-1.8.0\bin\java JavaScriptHello

From JavaScript:
   Hello world!

 

SJP (Scripting for the Java Platform) API

⇒⇒FAQ for Rhino JavaScript Java Library

2017-08-03, 224👍, 0💬