1

我正在尝试使用 ES4X/Graal 在 JavaScript 项目中扩展 Java 类。我要扩展的类具有需要重写的带有过载参数的方法。我知道您可以通过使用方括号表示法并指定类型(下面的示例)来调用特定的 Java 方法,但显然,根据 Graal/Oracle/Nashorn 文档,在覆盖时无法指定参数类型。因此,如果您有以下情况:

package com.mycomp;

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

您可以像这样在 JavaScript 中调用任一方法:

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

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

但是,在扩展时,您只能执行以下操作:

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

我希望能够仅扩展其中一种method(...)方法。那么具有不同返回类型的重载方法呢?

谢谢!

4

1 回答 1

-1

sj4js允许你做所有这些

此示例根据文档稍作修改...

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";
    }
}

您可以像访问 JS 对象一样访问该对象,并且该库负责选择适当的方法。

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"
}
于 2021-03-09T20:05:57.347 回答