- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我遇到了以下问题。我想在 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)));
编辑 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
中的 other
和 this
是不同的类型。 有没有办法从传递给 equals
的对象中转换或获取 _from
值?
解决方案
在 Tomasz 的回答中查看问题的解决方案。
Tomasz 干得好!谢谢。
PS:很遗憾,在 Nashorn 中没有简洁明了的方法来实现 equals
和 hashCode
。这对于原型(prototype)制作很有用。只需将其与此进行比较 :)
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(excludes="cost")
class Vertex {
int from, cost
}
最佳答案
在 Rhino 中你会使用:
var vertex = new JavaAdapter(java.lang.Object, new Vertex(1, 10));
hm.put(vertex, 10);
使 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");
参见: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.
您可以用这种方式扩展任何抽象类或接口(interface)。 (因为任何实现接口(interface)的匿名类也会扩展 Object,所以您也可以覆盖 equals
或 hashCode
方法)。
为了说明这一点,假设您有一个 JavaScript“原型(prototype)类”:
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 接口(interface)来启用此类包装器,而无需提供额外的方法实现(如上面示例中的 Compare
和 Comparable
) .
问题
正如您所指出的,以上述两种方式创建的对象都是具有固定“接口(interface)”的 Java 对象。因此,任何来自包装的 JavaScript 对象的方法或字段,如果没有被实现的接口(interface)或类明确指定,将无法从 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 对象上,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
关于java - Nashorn,Java 集合,如何在纯 javascript 中实现 equals 和 hashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25379340/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!