1

I'm trying to extend a Java class in a JavaScript project using ES4X/Graal. The class that I want to extend, has methods with overloeaded parameters that I need to override. I know that you can call a specific Java method by using the square brackets notation and specifying the type (example below), but, apparently, there's no way to specify the parameter types when overriding, per the Graal/Oracle/Nashorn documentation. So if you have the following:

package com.mycomp;

class A {
    public void method(String parameter) {...}
    public void method(int parameter) {...}
}

you can call either method in JavaScript like so:

var a = Java.type("com.mycomp.A");

a["method(String)"]("Some string parameter")
a["method(int)"](42)
a.method(stringOrIntParam)

However, when extending, you can only do the following:

var ClassAFromJava = Java.type("com.mycom.A");
var MyJavaScriptClassA = Java.extend(ClassAFromJava, {
    method: function(stringOrIntParam) {...}
}

I want to be able to extend only one of the method(...), um, methods. And what about overloaded methods with different return types?

Thanks!

1 Answers1

-1

The sj4js allows you to do all that.

This example is slightly modified from the documentation...

public class TestObject extends JsProxyObject {
    
    // the constructor with the property 
    public TestObject (String name) {
        super ();
        
        this.name = name;
        
        // we hvae to initialize the proxy object
        // with all properties of this object
        init(this);
    }

    // this is a mandatory override, 
    // the proxy object needs this method 
    // to generate new objects if necessary
    @Override
    protected Object newInstance() {
        return new TestClass(this.name);
    }

    // a method with a String parameter
    public String method (String s) {
        return "String";
    }

    // a method with a int parameter
    public String method (int i) {
        return "42";
    }
}

And you can access this object as you would access a JS object and the library takes care of selecting the appropriate method.

try (JScriptEngine engine = new JScriptEngine()) {
    engine.addObject("test", new TestClass("123"));
            
    // calling the method with the String parameter would 
    // result in calling the appropriate java method
    engine.exec("test.method('123')");
    // returns "String"

    // calling the method with the int parameter would 
    // result in calling the appropriate java method
    engine.exec("test.method(123)");
    // returns "42"
}