2

I'm trying to implement scripting endpoint in our application, but I have a problem: Is it possible to instantiate an object that is instance of abstract class with implemented methods? In Java it will look like:

SimpleObject obj = new SimpleObject("contructor arg0") {    
   public void doCustomAction() {
     System.out.println("Action");
   }
}

SimpleObject is an abstract class with abstract method doCustomAction How to do such thing via Java Scripting Engine? I'm trying to do in the following way:

obj1 = new SimpleObject("value1") {
    doCustomAction : function() {
       //Do smth.
    }
}

But engine throws such exception:

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException:
   error instantiating (JavaAdapter: first arg should be interface Class (<Unknown source>#1)): 
  class SimpleObject is interface or abstract (<Unknown source>#1) in <Unknown source> at line number 1

1 Answer 1

2

You could extend your abstract class in Java, something like MouseAdapter does with its interfaces, then in javascript you use this "adapter", like:

In Java:

public abstract class SimpleObject {
   abstract void doCustomAction();
}
public class SimpleObjectAdapter extends SimpleObject {
   void doCustomAction(){}
}

In JavaScript:

obj1 = new JavaAdapter(SimpleObjectAdapter,{
    doCustomAction : function() {
       //Do smth.
    }
});

Edit: You could do it without the "adapter", just do:

obj1 = new JavaAdapter(Packages.SimpleObject, {
   doCustomAction: function(){
      //Do smth.
   }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.