import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
public class RhinoTest {
public static void main(String[] args) {
Context context = Context.enter();
ScriptableObject scope = context.initStandardObjects();
ScriptableObject.putProperty(scope, "out", Context.javaToJS(new
LiveSite(), scope));
context.evaluateString(scope, "out.print('a');", "asdads", 0, null);
}
}
class LiveSite {
public void print(String a) {
System.out.println(a);
}
}
gives me the following exception:
Exception in thread "main" org.mozilla.javascript.EcmaError: TypeError:
Cannot find function print in object LiveSite@e70e30.
at
org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3654)
at
org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3632)
at org.mozilla.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3660)
at org.mozilla.javascript.ScriptRuntime.typeError2(ScriptRuntime.java:3679)
at
org.mozilla.javascript.ScriptRuntime.notFunctionError(ScriptRuntime.java:3743)
at
org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThisHelper(ScriptRuntime.java:2247)
at
org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThis(ScriptRuntime.java:2214)
at
org.mozilla.javascript.gen.c1._c0(asdads:0)
at org.mozilla.javascript.gen.c1.call(asdads)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:398)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3065)
at org.mozilla.javascript.gen.c1.call(asdads)
at org.mozilla.javascript.gen.c1.exec(asdads)
at org.mozilla.javascript.Context.evaluateString(Context.java:1104)
at RhinoTest.main(RhinoTest.java:9)
HI, I also have a lot of question about how to expose a object to js
engine, here is some expirence I can share:
first take a look at the rhino example:
rhino1_7R3pre/examples/CounterTest.java you can get from rhine
download,
this example shows that you should start your method name with a
preifx: "jsFunction_" and your class should be subclass of
ScriptableObject.
and I think there is another way you can expose method or variable to
js engine, you can extends the ScriptableObject and overwrite the get
and put methods. that make your class file work like a naitva js
object, for example: NativeDate, NativeArray. and I am working on it
and got no further steps.
: ) good lock
I got the same error you did (well, I had to add the static qualifier
on the LiveSite class to get it to compile).
I then added the public qualifier as well, and it worked fine.
public static class LiveSite {
public void print(String a) {
System.out.println(a);
}
}
Jeremy