Rhinoを使ってJavaからJavaScriptを呼び出す簡単なサンプル
本家チュートリアルサイトでは、こんな簡単なJavaからJavascriptを呼び出す実装が、今ひとつわかりにくかったので、備忘録的にエントリーしておきます。
import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.Scriptable; public class Sample_Rhino { public static void main(String[] args) throws Exception { Context context = Context.enter(); try { Scriptable scope = context.initStandardObjects(); context.evaluateString(scope, "function helloworld(arg){return 'hello ' + arg;}", "<cmd>", 1, null); Object fObj = scope.get("helloworld", scope); if (!(fObj instanceof Function)) { System.out.println("f is undefined or not a function."); } else { Object functionArgs[] = { "world" }; Function f = (Function)fObj; Object result = f.call(context, scope, scope, functionArgs); String report = "helloworld('world') = " + Context.toString(result); System.out.println(report); } } catch (Exception e) { throw e; }//end of try-catch }//end of mathod }//end of class