On Apr 2, 2:39 pm, Wernke <[email protected]> wrote:
> Hi all,
>
> I have a Java class 'Procedure' derived from ScriptableObject that has
> a public enum Result {OK, ERROR}. How can I make the enum values
> available to a script?
>
> As an example, say there is a method Procedure.setResult( Result r ),
> which I want to call from the script with an OK value.
>
> I found that with a given Procedure object proc I can do:
>
> proc.setResult( Packages.my.namespace.Procedure.Result.OK );
>
> but I find this clumsy.
>
> What would I have to do to be able to call
>
> proc.setResult( OK ) or at least proc.setResult( Result.OK )
>
> without any further import or such in the script? What I am actually
> looking for is a Java method on ScriptableObject that makes the const
> enum values visible and usable in the script, just similar to
> defineProperty().

If you are using ScriptableObject.defineClass() to set up your
Procedure host object then the finishInit() method is your friend.

http://www.mozilla.org/rhino/apidocs/org/mozilla/javascript/ScriptableObject.html#defineClass(org.mozilla.javascript.Scriptable,%20java.lang.Class)

You can use it to set up all kinds of properties on the constructor,
global scope, or prototype. For example, to set up the enum values as
constants in the Procedure constructor:

    public static void finishInit(Scriptable scope, FunctionObject
constructor, Scriptable prototype) {
        int flags = DONTENUM | READONLY | PERMANENT;
        constructor.defineProperty("OK", Context.toObject(Result.OK,
scope), flags);
        constructor.defineProperty("ERROR", Context.toObject
(Result.ERROR, scope), flags);
    }

or as global constants:

    public static void finishInit(Scriptable scope, FunctionObject
constructor, Scriptable prototype) {
        int flags = DONTENUM | READONLY | PERMANENT;
        ScriptableObject.defineProperty(scope, "OK", Context.toObject
(Result.OK, scope), flags);
        ScriptableObject.defineProperty(scope, "ERROR",
Context.toObject(Result.ERROR, scope), flags);
    }

I also tried to setting up the enum class as constant in the global
scope, but that didn't work, probably because of how enums and their
constants are represented within the jvm. Note that finishInit must be
declared public in order to work.

hannes

> Thanks for any suggestions,
>
> Wernke

_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino

Reply via email to