我想公開一個Java方法,以便它可以被任意腳本調用。該腳本應該能夠對返回值執行算術運算。Rhino:如何從JavaScript調用的Java方法返回一個Integer?
的問題是,雖然暴露方法返回一個Java Integer
,腳本實際上並沒有得到正規數,但org.mozilla.javascript.NativeJavaObject
一個實例。
下面是一些簡單的測試代碼,顯示的行爲:
public class RhinoTest
{
public static void main(String[] args)
{
String script = "foo.getBar() + 1";
Context context = Context.enter();
ScriptableObject scriptableObject = context.initStandardObjects();
ScriptableObject.putProperty(scriptableObject, "foo", new Foo());
Object result = context.evaluateString(scriptableObject, script, "FooBar", 1, null);
Context.exit();
System.out.println(result);
}
public static class Foo
{
public Integer getBar()
{
return 9;
}
}
}
預期的結果是10
,但該腳本返回91
。
那麼我怎樣才能讓getBar()
內部腳本發生的調用實際返回一個正常的Javascript數據類型呢?請注意,我不想通過添加unwrap()
調用,等來更改腳本代碼。
嘗試'¨foo.getBar()'+ 1 – subodh 2013-02-11 09:54:23