biquillo
biquillo

Reputation: 6539

Overload a Java method using Javascript Rhino

I have a class such the one below and I would like to override both methods using Javascript Rhino, any suggestions?

Thanks in advance!!

class MyClass() {
  public void method1(); 
  public void method2(); 

  MyClass() {
    method1();
    method2();
  } 
}

Upvotes: 3

Views: 1537

Answers (2)

stevestorey
stevestorey

Reputation: 606

While I've not tried this in an Android environment, Rhino does support a JavaAdapter construct - as seen at: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java#The_JavaAdapter_Constructor which allows you to create a JS object defining the correct methods, and then to create effectively a wrapper between a single superclass, and/or one or more interfaces. In this case, something like:

var o = {
  method1: function() {
    print('method1');
  },
  method2: function() {
    print('method2');
  }
}

//This line should instantiate the child class, with
//method1 + method2 overridden called within the constructor
var instanceThatIsAMyClass = new JavaAdapter(com.example.MyClass, o);

Upvotes: 1

gustafc
gustafc

Reputation: 28865

The last time I used it, the JDK bundled Rhino didn't support extending classes (only implementing SAM interfaces), but Mozilla's Rhino does support overriding classes. Check out the JavaAdapter: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java#The_JavaAdapter_Constructor

Upvotes: 2

Related Questions