【问题标题】:Extending Java Classes and Overriding Methods with Overloaded Parameters in ES4X/Graal在 ES4X/Graal 中使用重载参数扩展 Java 类和覆盖方法
【发布时间】:2021-01-01 17:33:15
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: javascript java graalvm graaljs


    【解决方案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"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多