Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  } 
}
like image 973
biquillo Avatar asked Feb 01 '26 20:02

biquillo


2 Answers

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

like image 149
gustafc Avatar answered Feb 04 '26 08:02

gustafc


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);
like image 39
stevestorey Avatar answered Feb 04 '26 10:02

stevestorey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!