Vamsi Emani
Vamsi Emani

Reputation: 10312

Rhino: Access Java interface variables in Javascript implementation

Rhino: How to access Java interface variables in Javascript implementation?

I expose a java interface for some other party to let them provide an implementation for the same in javascript.

public interface APIInterface{

    public static APIUtils util = new APIUtils();

    public ArrayList getAllObjects(Object aTransaction);
}

Javascript implementation:

/** Core Interface Method **/
new Object() {

  getAllObjects: function(tran) {
        tran.set(..); //OK  
        tran.set(..); //OK
        util.callSomeFunction(); //Fails here..Rhino doesn't understand util.. 
  }    

}

I want the javascript implementation of the interface to understand the interface variable util without having to pass it as an additional argument to the function or by adding it to the ScriptEngine. Is this technically possible?

Upvotes: 2

Views: 2066

Answers (1)

McDowell
McDowell

Reputation: 108969

For the interface...

package foo;
public interface Iface {
  String X = "Hello, World!";
  void invoke();
}

...static member¹ X can be accessed two ways.

1) Via the type:

var x = Packages.foo.Iface.X;

2) Via reflection:

var impl = new Packages.foo.Iface({
  invoke : function () {
    var x = this.getClass().getField("X").get(null);
    java.lang.System.out.println(x);
  }
});
impl.invoke();

Tested on Rhino 1.7R4.

¹All variables are implicitly public static final on interfaces.

Upvotes: 1

Related Questions