2
1

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 3 years have passed since last update.

Javaで実行したJavaScriptからJavaメソッドをコールする

Last updated at Posted at 2018-02-14

■本家のドキュメント(1)
https://docs.oracle.com/javase/jp/6/technotes/guides/scripting/programmer_guide/
■本家のドキュメント(2)
https://developer.mozilla.org/ja/docs/Rhino/Scripting_Java


package pkg;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class HelloJavaScript {
	public void run() {
		System.err.println("hello!");
	}
	public static void main(String[] args) {
		// see
		// https://developer.mozilla.org/ja/docs/Rhino/Scripting_Java
		// These packages are likely not in the java package, so you'll need to
		// prefix the package name with "Packages."

		// Get the JavaScript engine
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		String script = "" //
				+ "var obj = new Packages.pkg.HelloJavaScript();" //
				+ "obj.run();" //
		;
		try {
			engine.eval(script);
		} catch (ScriptException e) {
			e.printStackTrace();
		}
	}
}
2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?