Subj : Re: Calling a compiled script with arguments To : redcoat From : Igor Bukanov Date : Mon Dec 20 2004 10:55 pm redcoat wrote: > I've got everything running, but having problems with new objects being > created unexpectedly... > > I'm using your code as follows: > > private Scriptable prepareExecScope(Scriptable sharedScope, Handler > client) > throws EvaluatorException, JavaScriptException, IllegalAccessException, > InstantiationException, InvocationTargetException, > ClassDefinitionException, PropertyException > { > Context cx = Context.enter(); > try > { > Scriptable scope = cx.newObject(sharedScope); > > scope.setPrototype(sharedScope); > scope.setParentScope(null); > > ScriptableObject.defineClass(scope, MFPHandler.class); > Scriptable jsClient = cx.newObject(scope, "MFPClient"); > scope.put("client", scope, jsClient); > > return scope; > } > finally > { > Context.exit(); > } > } > > The problem comes when I call the ScriptTest - I am passing in an > MFPClient object that I have already instantiated, and want to use > that, with it's member variables, with this particular script > execution. > > However I see the MFPClient constructor getting called twice more, with > the ScriptableObject.defineClass, and cx.newObject(scope, "MFPClient") > calls. Thus the script calls an object that has none of the member > variables set. You should call ScriptableObject.defineClass(scope, MFPHandler.class) during initialization of the shared scope so all the object/machinery of exposing your object would go to the shared scope. That machinery includes MFPClient constructor and MFPClient.prototype object to support the standard JS-prototype based inheritance. It also explains why you got MFPHandler constructor executed twice: the first time during ScriptableObject.defineClass call to construct prototype object and the second time when you call cx.newObject(scope, "MFPClient"); > Is there any way to have the script call an pre-instantiated java > object, which has particular member variables before the script is run. Sure, just use direct scripting of Java objects also known as LiveConnect and replace > ScriptableObject.defineClass(scope, MFPHandler.class); > Scriptable jsClient = cx.newObject(scope, "MFPClient"); > scope.put("client", scope, jsClient); by something like: public class Example { int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String printValue(int base) { return Integer.toString(value, base); } } .... Example example = new Example(); example.value = 100; scope.put("client", scope, Context.javaToJS(example, scope)); Then your scripts can use client.value = client.value + 100; var str = client.printValue(10); etc.. Regards, Igor .