12
8

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

計算式をデータベースにマスタ登録するような場合に使うのね。
(いま、そういう必要性が出ただけ。。)

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class Test {
	public static void main(String[] args) throws Exception {
    	String script = "result=num*2";

    	ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
    	Compilable ce = (Compilable) engine;
        CompiledScript cs = ce.compile(script);
        engine.put("num", 1);
        cs.eval();
        Object result = engine.get("result");
        if(result != null) {
        	System.out.println("result=" + result.toString());
        }
	}
}
12
8
2

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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?