Rhinoを使ってJavaから外部JavaScriptファイルを呼び出す簡単なサンプル

なんか前にチャレンジした時は妙に苦労した気がするけど、難なくできてしまった。
一応、エントリーしときます。

なお、test.js はEclipseプロジェクト直下に配置。

import java.io.FileReader;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;


public class Sample_Rhino2 {

	public static void main(String[] args) throws Exception 
	{
		
		Context context = Context.enter();
		
		try
		{
			FileReader reader = new FileReader("test.js");
			
			Scriptable scope = context.initStandardObjects();
			context.evaluateReader(scope, reader, "<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