在 ES4X/Graal 中使用重载参数扩展 Java 类和覆盖方法

问题描述

我正在尝试使用 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(...) 中的一种,嗯,方法。那么具有不同返回类型的重载方法呢?

谢谢!

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...