4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java で JavaScript を実行する

Posted at
package hello.javax.script;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class HelloScriptEngine3 {

	public static void main(String[] args) {

		System.out.println("[Hello,JavaScript]");

		// Hello, JavaScript
		{
			// Get the JavaScript engine
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");

			// 実行する
			String script1 = "var msg=\"Hello, JavaScript\"; println(msg);";
			try {
				// JavaScript 組み込み関数 println で出力
				engine.eval(script1); // Hello, JavaScript
			} catch (ScriptException e) {
				e.printStackTrace();
			}
		}

		System.out.println("[Object]");
		// JSON
		{
			// Get the JavaScript engine
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");

			String script2 = "var o = {x:1,y:2}; println(o.x);";
			try {
				engine.eval(script2); // 1
			} catch (ScriptException e) {
				e.printStackTrace();
			}
		}

		System.out.println("[function]");
		// Function definition and call
		{
			// Get the JavaScript engine
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");
			// 関数の定義と変数への代入
			String script1 = "function f1(x,y){return x+y;} var b = f1(1,3);";
			try {
				engine.eval(script1);
				// 変数の取り出し
				System.out.println(engine.get("b")); // 4.0
			} catch (ScriptException e) {
				e.printStackTrace();
			}
		}

		System.out.println("[function2]");
		{
			// Get the JavaScript engine
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");
			// 関数の定義
			String script1 = "function myfunc(a,b){return a+b;}";
			try {
				engine.eval(script1);
			} catch (ScriptException e) {
				e.printStackTrace();
			}

			{
				String script2 = "b = myfunc(100,-30);";
				try {
					engine.eval(script2);
					System.out.println(engine.get("b")); // 70.0
				} catch (ScriptException e) {
					e.printStackTrace();
				}
			}

		}
	}

}

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?