Skip to content

Create a way to expose members of a java object on the global scope of the script context #295

@brentco

Description

@brentco

Hello,

I am registering certain objects that contain methods that I want to be exposed in the script using Context#putMember(name, object).

For some of these methods I want them to be exposed in a "namespace", for example:

public class IVRModuleRuntime extends ScriptModuleRuntime<IVRModule> {
    @Api
    public void say(String message) {
        
    }
}

should be exposed under the IVR "namespace" so I would do context.putMember("IVR", ivrModuleRuntime):

IVR.say("this is IVR");

In contrast, I'd like this module to be exposed as root functions:

public class DebugModuleRuntime extends ScriptModuleRuntime<DebugModule> {

    @Api
    public void info(String message, Object... args) {
        
    }
}

I want to ultimately expose at the root, so inside the script I can do:

var test = "test";
info("this is a {}", test);

I couldn't find an easy way to do this, so I came up with this:
https://gist.github.com/brentco/748be33f93e47c09c11d5a8e1b619a2a

Basically, I use reflection and a ProxyExecutable to invoke the right method in the module runtime based on the method's name and a list of arguments. I manually try to match that up to the right method and then call it.

It seems to be working for now, but this is not something I want to rely on. I doubt it has good performance and there are probably edge cases and whatnot. So I'd like to see this being implemented properly inside the API :)

Metadata

Metadata

Assignees

Labels

questionFurther information is requested

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions