How can I subclass (extend) a Java class using Rhino when I need to use a constructor that takes an argument?

I have a class like the following: this is part of the library, and I canโ€™t change it at all (if I could, I would just overwrite it or subclass it in Java)

public class FirstClass { public FirstClass(SecondClass arg) { ... } public ThirdClass aMethod() { ... } ... } 

I want to create a Javascript object using Rhino (so no comment that JavaScript is different from Java, I know that), but override the "aMethod" method.

So, in Java, I would do this ...

 public class MySpecialFirstClass extends FirstClass { public FirstClass(SecondClass arg) { super(arg); } public ThirdClass aMethod() { ThirdClass toReturn = super.aMethod(); //My implementation goes here. return toReturn; } ... } 

But I can not do it in Javascript. Things I've tried so far ...

 function js_FirstClass(arg) { var temp = JavaAdaptor(FirstClass, { '<init>': FirstClass, aMethod: function() { var toReturn = super.aMethod(); //Do stuff return toReturn; } }); return temp; } 

I also tried ...

 var myClass = new FirstClass(secondClass); myClass.aMethodOld = myClass.aMethod; myClass.aMethod = function() { var toReturn = aMethodOld(); //Do stuff return toReturn; } 

Other offers?

+4
source share
1 answer

Try the prototype approach:

 function newFirstClass(arg) { // Create hidden instance var inst = new FirstClass(arg); return { aMethod: function() { var result = inst.aMethod(); // ... do stuff return result; } // forward every other call directly to inst otherMethod: function() { return inst.otherMethod(); } // etc... } } 

So the idea is that you create a JavaScript object that behaves like an instance of FirstClass , offering the same methods (you need to register each method manually) and passing calls to the hidden instance inst .

Not working with instanceof , but useful if you need duck typing .

0
source

All Articles