views:

252

answers:

1

Rhino provides Scriptable interface and ScriptableObject helper class to implement a javascript object backed by a java object.

When ScriptableObject is constructed, its methods with names starting with jsFunction___, jsStaticFunction___, jsGet___, jsSet___, jsConstructor are automatically defined for the javascript object. This way you can defined funations, static frunctions, instance properties (by its accessors), and constructor.

The question is how to define static properties?

By static properties I mean properties on the constructor, like static methods are methods on the constructor.

The only way I see for now is to use finishInit method, and define static properties manually. But what is the right way?

+1  A: 

Currently I have something like this on my mind:

public class MyObject extends ScriptableObject {

@Override
public String getClassName() {
    return "MyObject";
}

// define static properties
public static void finishInit(Scriptable scope, FunctionObject ctor, Scriptable proto) {
    ctor.defineProperty("PROP_ONE", 1, READONLY);
    ctor.defineProperty("PROP_TWO", 2, READONLY);
    ctor.defineProperty("PROP_THREE", 3, READONLY);
}

Are there other ways? And is this way correct?

IMPORTANT: Note that constructor for MyObject is not yet defined in scope, when finishInit is called. In order to define static properties, which are instances of MyObject, use the following syntax:

public static void finishInit(Scriptable scope, FunctionObject ctor, Scriptable proto) {
    Context cx = Context.getCurrentContext();
    Scriptable myObjectInstance = ctor.construct(cx, scope, new Object[] { /* args */ });
    ctor.defineProperty("PROP", myObjectInstance, READONLY);
    ....
}
vsg