Nashorn,Java集合,如何在纯JavaScript中实现equals和hashCode

8
我遇到了以下问题。我想在Nashorn脚本中使用java.util.HashMap和java.util.PriorityQueue,其中我需要将特定的自定义对象作为HashMap中的键,并且还需要使用HashMap.containsKey()来检查Map中是否存在该键(另一种选择是检查Collection.contains(Object o)中的对象)。
因此,显然,我需要基于某些字段值在我的对象中实现equals和hashCode方法。
例如:
1.尝试使用JavaScript。由于JavaScript没有这些方法而无法工作。请参见样例1和样例2。
2.扩展java.lang.Object。样例3。部分工作正常,方法正在被调用。但是
-如何插入具有参数的构造函数?
-如何从this:[object Object]转换为其他:jdk.nashorn.javaadapters.java.lang.Object@0或反之亦然?
3.在Java中实现我的自定义类并在JavaScript中进行扩展。样例4。它可以工作。但是如果必须使用Java,那么我需要Nashorn吗?
var PriorityQueue = java.util.PriorityQueue;
var HashMap = java.util.HashMap;
var Integer = java.lang.Integer;

// Sample 1
// Doesn't work, equals and hashCode are not being invoked
function Vertex1(from, cost) {
    this.from = from;
    this.cost = cost;

    this.equals = function(other) { return this.from == other.from; }
    this.hashCode = function() { return Integer.hashCode(this.from); }
}

var hm = new HashMap();
hm.put(new Vertex1(1, 10), 10);
hm.put(new Vertex1(1, 20), 21);
// Prints size is 2, but I'd like to see 1
print("HashMap size: " + hm.size());
// Prints false
print("HashMap1 contains: " + hm.containsKey(new Vertex1(1, 20)));

// ------------------------------------------------------------------
// Sample 2
// Doesn't work, equals and hashCode are not being invoked
function Vertex1(from, cost) {
    this.from = from;
    this.cost = cost;
}
Vertex1.prototype = {
    equals : function(other) { return this.from == other.from; },
    hashCode : function() { return Integer.hashCode(this.from); },
}
var hm = new HashMap();
hm.put(new Vertex1(1, 10), 10);
hm.put(new Vertex1(1, 20), 21);
// Prints size is 2, but I'd like to see 1
print("HashMap size: " + hm.size());
// Prints false
print("HashMap1 contains: " + hm.containsKey(new Vertex1(1, 20)));

// ------------------------------------------------------------------
// Sample 3
// Works partially, Methods are being invoked. But 

// 1. How to plugin construstor with parameters?
// 2. How to do the cast from this:[object Object] to other:jdk.nashorn.javaadapters.java.lang.Object@0, or vice versa

var JObject = Java.type("java.lang.Object");
var Vertex2 = Java.extend(JObject, {
    from : 0,
    equals : function(other) { return this.from.equals(other.from); },
    hashCode : function() { return Integer.hashCode(this.from); },
});
var hm = new HashMap();
// How to implement constructor for new Vertex2(10, 10)?
hm.put(new Vertex2(), 10);
hm.put(new Vertex2(), 21);
// Prints size is 2, because hashCode is the same and equals returns false
print("HashMap size: " + hm.size());
// Prints false, because equals returns false
print("HashMap1 contains: " + hm.containsKey(new Vertex2()));

// ------------------------------------------------------------------
// Sample 4
// com.arsenyko.MyObject is implemented in Java, Works, but Nashorn is ambiguous then!!!
var MyObject = Java.type("com.arsenyko.MyObject");
var Vertex2 = Java.extend(MyObject, {});
var hm = new HashMap();
hm.put(new Vertex2(1, 10), 10);
hm.put(new Vertex2(1, 20), 21);
print("HashMap size: " + hm.size());
print("HashMap1 contains: " + hm.containsKey(new Vertex2(1, 10)));

编辑1

@Tomasz,谢谢。我看到了所有提到的链接。但是似乎存在一些未经记录的内容。几乎放弃了Nashorn。我得出了以下部分解决方案,方法被调用,构造函数被使用,但如何在equals方法中将other.from转换为原始对象的from字段(这段代码为每个Vertex实例产生不同的类)

//load("nashorn:mozilla_compat.js");
var PriorityQueue = java.util.PriorityQueue;
var HashMap = java.util.HashMap;
var Integer = java.lang.Integer;

function Vertex1(from, cost) {
    this.from = from;
    this.cost = cost;

    this.equals = function(other) {
        var value1 = this.from;
        // How to get other.from here???
        var value2 = other.from;
        print('value1=' + value1 + ' value2=' + value2);
        print(other);
        var eq = value1.equals(value2);
        print('equals is ' + eq);
        return eq;
    }
    this.hashCode = function() {
        var hashCode = Integer.hashCode(this.from);
        print('hashCode is ' + hashCode);
        return hashCode;
    }

    var JObject = Java.type("java.lang.Object");
    // return Java.extend(JObject, this); // doesn't work
    // return this; // doesn't work
    // return new JavaAdapter(java.lang.Object, this); // Works! with load("nashorn:mozilla_compat.js");
    var Type = Java.extend.apply(Java, [JObject]);
    return new Type(this);
}

var hm = new HashMap();
hm.put(new Vertex1(1, 10), 10);
hm.put(new Vertex1(1, 20), 21);
// Prints size is 2, but I'd like to see 1
print("HashMap size: " + hm.size());
// Prints false
print("HashMap contains: " + hm.containsKey(new Vertex1(1, 20)));

编辑2

感谢Tomasz指出,使用具有类特定实现对象的Java.extend()函数的每个调用都会产生一个新的Java适配器类。因此,我们需要一个Object Extender并使用该类型实例化对象,正如他在示例中所展示的那样。我稍微修改了它,以便使用相同的Object Extender生成具有相同类的实例,无论是使用工厂还是直接构造函数。

var HashMap = java.util.HashMap;
var JInteger = java.lang.Integer;
var JObject = Java.extend(java.lang.Object);

var createVertex = (function() {
    var
    _equals = function(other) {
        print(this + ' vs ' + other);
        return this._from === other.from;
    };
    _hashCode = function() {
        var hashCode = JInteger.hashCode(this._from);
        print(hashCode);
        return hashCode;    
    };
    return function(from, cost) {
        return new JObject() {
            _from : from,
            _cost : cost,
            equals : _equals,
            hashCode : _hashCode,
        }
    }
})();

var JSVertex = function(from, cost) {
    return new JObject() {
        _from : from,
        _cost : cost,
        equals : function(other) {
            print(this + ' vs ' + other);
            return this._from === other._from;
        },
        hashCode : function() {
            var hashCode = JInteger.hashCode(this._from);
            print(hashCode);
            return hashCode;
        }
    }
}

var v1 = JSVertex(1, 10);
var v2 = JSVertex(1, 20);
//var v1 = createVertex(1, 10);
//var v2 = createVertex(1, 20);
var v3 = createVertex(1, 20);
print(v1.class === v2.class); // returns true
print(v2.class === v3.class); // returns true
var hm = new HashMap();
hm.put(v1, 10);
hm.put(v2, 21);
print("HashMap size: " + hm.size()); // Prints 2, but I'd like to see 1
print("HashMap contains: " + hm.containsKey(v3)); // Prints false

然而,还存在一个问题: equals 的参数类型是 jdk.nashorn.javaadapters.java.lang.Object,换句话说,equals 中的otherthis是不同的类型。 有没有办法将对象传递给equals并强制转换或获取_from值?

解决方案

请参见Tomasz的答案中的解决方案。

干得好,Tomasz!谢谢。

PS:非常遗憾,在Nashorn中没有简洁明了的方法来实现equalshashCode。 这对原型设计很有用。只需比较一下:

import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(excludes="cost")
class Vertex {
   int from, cost
}

嗨,我的答案有一些错误。我已经修复了它们(再次编辑了答案)。使用Nashorn似乎比使用Rhino更加复杂。 - Tomasz Gawel
你好,有两个注意事项:1. 如果JSVertex是一个返回new JObject() { ...的函数,那么在调用它时不需要调用new - 只需调用var v1 = JSVertex(1, 10);;2. 在你的createVertex中,如果你没有在匿名函数调用中隐藏任何“私有”变量(这是我之前示例中的情况),则不需要使用匿名函数来返回实际函数。 - Tomasz Gawel
关于在JavaScript中读取(和设置)Java对象的自定义属性 - 这似乎是Nashorn中的另一个缺陷(我不记得Rhino中是什么样子的) - 我稍后会对我的答案进行另一个编辑来解决它。 - Tomasz Gawel
@tomasz-gawel 这与JSAdapter有关吗? - Arseny Kovalchuk
1
单独一行的那个 var 看起来很奇怪。在 _equals 的定义后面应该是逗号而不是分号吗? - David Conrad
显示剩余5条评论
1个回答

6
在Rhino中,您需要使用:
var vertex = new JavaAdapter(java.lang.Object, new Vertex(1, 10));
hm.put(vertex, 10);

为了让JavaScript方法覆盖与java.lang.Object中同名的Java方法(参见此处),可以使用特定的构造函数。可能在Nashorn中有类似的结构。
编辑:可以在Nashorn中使用Rhino语法,只需添加以下一行代码:
load("nashorn:mozilla_compat.js");

请参阅:https://wiki.openjdk.java.net/display/Nashorn/Rhino+Migration+Guide 编辑说明:使用Nashorn似乎更加复杂。
// we will need a factory method
var createVertex = (function() { // i hope you are familiar with "inline" function calls

    // private variables used in every call of factory method - but initialized once
    var 
        JObjExtender = Java.extend(Java.type("java.lang.Object")),
        JInteger = Java.type("java.lang.Integer"),
        _equals = function(other) { 
            return this.from === other.from; 
        },
        _hashCode = function() { 
            return JInteger.hashCode(+this.from); // leading "+" converts to number
        };

    // the "actual" factory method
    return function(from, cost) {
        return new JObjExtender() {
            from : from,
            cost : cost, 
            equals : _equals,
            hashCode : _hashCode
        };
    };
})();

var vertex = createVertex(1, 10);
hm.put(vertex, 10);

请查看http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html

更有趣的是,如果您创建多个实例,如下所示:

var v1 = createVertex(1, 10);
var v2 = createVertex(1, 20);

然后它们属于同一类(我预期它们是Object的两个匿名子类的实例)。

var classEquals = (v1.class === v2.class); // produces : true

一项技巧:

虽然在Nashorn中,您不能像以下方式那样即时扩展非抽象类:

var v1 = new java.lang.Object(new JSVertex(10, 10));
// produces: TypeError: Can not construct java.lang.Object with the passed
// arguments; they do not match any of its constructor signatures.

你可以通过这种方式扩展任何抽象类或接口。(由于任何实现接口的匿名类也继承了Object,因此你也可以重写equals或hashCode方法)。
为了说明这一点,考虑你有一个JavaScript“原型类”:
var JSVertex = function (from, cost) {
    this.from = from;
    this.cost = cost;
};
JSVertex.prototype = {
    equals : function(other) { 
        return this.from === other.from; 
    },
    hashCode : function() { 
        return java.lang.Integer.hashCode(+this.from); // leading "+" converts to number
    },
    compare : function(other) {
        return this.from - (+other.from);
    }
};

现在你可以按以下方式创建其“Java封装”的实例:
var v1 = new java.lang.Comparable(new JSVertex(10, 10));
print(v1.class); 
// produces both: class jdk.nashorn.javaadapters.java.lang.Object and
// class jdk.nashorn.javaadapters.java.lang.Comparable

var v2 = new java.lang.Comparable(new JSVertex(11, 12));
print(v2 instanceof java.lang.Object); // produces true
print(v2 instanceof java.lang.Comparable); // produces true

了解到你可以创建一个空的Java接口,以启用这种包装器,而不需要提供额外的方法实现(例如在上面关于Comparable的例子中的compare)。

问题

正如您所指出的,以上两种方式创建的对象都是具有固定“接口”的Java对象。因此,如果从未通过已实现的接口或类明确指定包装的JavaScript对象中的任何方法或字段,则无法从JavaScript中访问它们。

解决方案

经过一些摆弄,我找到了解决上述问题的方法。其中一个关键是来自Nashorn脚本API的jdk.nashorn.api.scripting.AbstractJSObject类。

考虑我们有JSVertex "javascript类"(与上面介绍的非常相似):

var JSVertex = function (from, cost) {
    this.from = +from;
    this.cost = +cost;
};
JSVertex.prototype = {
    equals : function(other) { 
        print("[JSVertex.prototype.equals " + this + "]");
        return this.from === other.from;
    },
    hashCode : function() { 
        var hash = java.lang.Integer.hashCode(this.from);
        print("[JSVertex.prototype.hashCode " + this + " : " + hash + "]");
        return hash;
    },
    toString : function() {
        return "[object JSVertex(from: " + 
            this.from + ", cost: " + this.cost + ")]";
    },
    // this is a custom method not defined in any Java class or Interface
    calculate : function(to) { 
        return Math.abs(+to - this.from) * this.cost;
    }
};

让我们创建一个函数,允许我们以这种方式包装Java对象,使得JavaScript对象中的任何同名方法都会“扩展”相应的Java对象方法。

var wrapJso = (function() { 

    var 
        JObjExtender = Java.extend(Java.type(
            "jdk.nashorn.api.scripting.AbstractJSObject")),
        _getMember = function(name) {
            return this.jso[name];
        },
        _setMember = function(name, value) {
            this.jso[name] = value;
        },
        _toString = function() { 
            return this.jso.toString();
        };

    return function(jsObject) {
        var F = function() {};
        F.prototype = jsObject;
        var f = new F();
        f.jso = jsObject;
        f.getMember = _getMember;
        f.setMember = _setMember;
        f.toString = _toString; // "toString hack" - explained later
        return new JObjExtender(f);
    };
})();

最后,写完这些,让我们看看它如何运行。

创建一个JSVertex对象的包装器并对其进行一些测试:

var wrapped = wrapJso(new JSVertex(11,12));

// access custom js property and method not defined in any java class 
// or interface.
print(wrapped.from);
print(wrapped.calculate(17));

print("--------------");

// call toString() and hashCode() from JavaScript on wrapper object
print(wrapped.toString());
print(wrapped.hashCode());

print("--------------");

// Use StringBuilder to make Java call toString() on our wrapper object.
print(new java.lang.StringBuilder().append(wrapped).toString() );
// see hack in wrapJso() - for some reason java does not see 
// overriden toString if it is defined as prototype member.

// Do some operations on HashMap to get hashCode() mehod called from java
var map = new java.util.HashMap();
map.put(wrapped, 10);
map.get(wrapped);

wrapped.from = 77;
map.get(wrapped);

print("--------------");

// let's show that modyfing any of pair: wrapped or jso touches underlying jso.
var jso = new JSVertex(17,128);
wrapped = wrapJso(jso);
print(wrapped);
jso.from = 9;
wrapped.cost = 10;
print(wrapped);
print(jso);
print(jso == wrapped);

输出结果:
11
72
--------------
[object JSVertex(from: 11, cost: 12)]
[JSVertex.prototype.hashCode [object JSVertex(from: 11, cost: 12)] : 11]
11
--------------
[object JSVertex(from: 11, cost: 12)]
[JSVertex.prototype.hashCode [object JSVertex(from: 11, cost: 12)] : 11]
[JSVertex.prototype.hashCode [object JSVertex(from: 11, cost: 12)] : 11]
[JSVertex.prototype.hashCode [object JSVertex(from: 77, cost: 12)] : 77]
--------------
[object JSVertex(from: 17, cost: 128)]
[object JSVertex(from: 9, cost: 10)]
[object JSVertex(from: 9, cost: 10)]
false

谢谢,我编辑了帖子,但仍有一个问题,如何从jdk.nashorn.javaadapters.java.lang.Object访问other.from,您可能能够提供帮助。 - Arseny Kovalchuk
抱歉我在之前的回答中犯了一些错误,导致你跟着走了。问题在于 Java.extend(Java.type("java.lang.Object"), jsObject) 实际上并没有创建一个新对象,而是为创建新扩展对象提供了一个“模板”。在我最后一次编辑后,答案现在应该显示正确的使用场景。 - Tomasz Gawel
在说完这句话后,我倾向于在Java中定义数据结构 - 而只会在JavaScript中“编写脚本”。;) - Tomasz Gawel
稍微修改了你的代码,你发现了一个好技巧,但正如你所提到的,它需要用Java编码。因此,如果我必须在Java中编写其中的一部分,那么我根本不需要使用“技巧”的Nashorn :)。这显然是Java、Scala、Groovy等语言中的“无问题”实现。但我很失望,JDK附带了一种脚本语言,只需使用文本编辑器并从控制台运行即可非常有用,但没有明显的方法来编写基本的脚本! - Arseny Kovalchuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接