Ars*_*huk 8 javascript java equals hashcode nashorn
我遇到了以下问题.我想使用java.util.HashMap
,并java.util.PriorityQueue
在犀牛脚本,在这里我需要使用特定的自定义对象为在HashMap的关键,并且还使用HashMap.containsKey()
以检查是否有在Map中的键(另一种选择是检查的对象Collection.contains(Object o)).
所以,显然,我需要在我的对象中基于一些字段值实现equals和hashCode.
例如:
试图使用JavaScript.由于JavaScript没有那些方法不起作用.请参阅样品1和样品2
扩展java.lang.Object.样本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)));
Run Code Online (Sandbox Code Playgroud)
编辑1
@Tomasz,谢谢.已经看过所有提到的链接.但是,虽然存在一些无证件.几乎放弃了Nashorn.得出以下部分解决方案,正在调用方法,正在使用构造函数,但是如何other.from
在equals
方法中强制转换以访问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)));
Run Code Online (Sandbox Code Playgroud)
编辑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
Run Code Online (Sandbox Code Playgroud)
然而,有一个仍然是一个问题,的参数的类型equals
就是jdk.nashorn.javaadapters.java.lang.Object
,换句话说,other
和this
里面equals
是不同的类型.有没有办法,_from
从传递给对象的对象中转换或获取值equals
?
解决方案
在Tomasz的答案中看到问题的解决方案.
伟大的工作Tomasz!谢谢.
PS:这是非常可悲的是没有实现干脆利落和直接的方式equals
,并hashCode
在犀牛.它对原型设计很有用.只是比较一下:)
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(excludes="cost")
class Vertex {
int from, cost
}
Run Code Online (Sandbox Code Playgroud)
在Rhino中你会使用:
var vertex = new JavaAdapter(java.lang.Object, new Vertex(1, 10));
hm.put(vertex, 10);
Run Code Online (Sandbox Code Playgroud)
使JavaScript方法从java.lang.Object中覆盖相同的命名Java方法(参见参考https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java#The_JavaAdapter_Constructor)
也许Nashorn有类似的结构.
编辑:
您可以在Nashorn中使用Rhino语法.只是把线:
load("nashorn:mozilla_compat.js");
Run Code Online (Sandbox Code Playgroud)
请参阅: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);
Run Code Online (Sandbox Code Playgroud)
请参阅 http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html
更有趣的是,如果您创建多个实例,如下所示:
var v1 = createVertex(1, 10);
var v2 = createVertex(1, 20);
Run Code Online (Sandbox Code Playgroud)
然后它们属于同一类(我希望它们是两个匿名太阳镜的实例Object
).
var classEquals = (v1.class === v2.class); // produces : true
Run Code Online (Sandbox Code Playgroud)
一个恶作剧:
虽然在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.
Run Code Online (Sandbox Code Playgroud)
您可以通过这种方式扩展任何抽象类或接口.(并且任何实现接口的匿名类也会扩展Object,因此您也可以覆盖equals
或hashCode
方法).
为了说明这一点,请考虑使用JavaScript"prototype-class":
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);
}
};
Run Code Online (Sandbox Code Playgroud)
现在你可以创建它的"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
Run Code Online (Sandbox Code Playgroud)
知道您可以创建一个空的Java接口来启用此类包装器,而无需提供其他方法实现(如上面compare
的示例Comparable
所示).
问题
正如您所指出的,上面提到的两种方式创建的对象都是具有固定"接口"的Java对象.因此,无法从javascript访问包装的JavaScript对象中的任何方法或字段,这些方法或字段尚未由实现的接口或类显式指定.
解决方案
经过一番摆弄后,我找到了解决上述问题的方法.它的关键是jdk.nashorn.api.scripting.AbstractJSObject
来自Nashorn脚本API的类.
考虑一下我们有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;
}
};
Run Code Online (Sandbox Code Playgroud)
让我们创建一个函数,它允许我们以这种方式将Java Object包装在任何JavaScript对象上,来自JavaScript对象的任何同名方法将"扩展"相应的Java Object方法.
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);
};
})();
Run Code Online (Sandbox Code Playgroud)
最后写了所有让我们看到它的工作.
在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);
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)