On 8月9日, 上午2时35分, Jonathan Scott <[email protected]> wrote: > I guess I'm missing something obvious from the documentation, but I > can't figure out how to let the javascript access a Java object. I > guess the error means it can access it but for some reason can't access > the method. Can anyone correct me? > > 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 lives...@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:37-43) > at > > org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThisHelper(ScriptRun-time.java:2247) > at > > org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThis(ScriptRuntime.j-ava: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 _______________________________________________ dev-tech-js-engine-rhino mailing list [email protected] https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino
