我有一些遗留代码(编译并成功地使用JDK 7u55运行),类似于以下内容:
private static class MyHashMap extends HashMap {
static Method getEntryMethod;
static {
try {
getEntryMethod = HashMap.class.getDeclaredMethod("getEntry", Object.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyHashMap myHashMap = new MyHashMap();
}在尝试切换到JDK 8u31之后,它失败了,因为:
java.lang.NoSuchMethodException: java.util.HashMap.getEntry(java.lang.Object)发布于 2015-02-16 14:08:51
看起来它被getNode()取代了,它返回一个Node (Map.Entry<K,V>的一个不同的实现)。如果必须使用此方法,则必须更改代码。使用包私有方法存在风险。它们可以消失。
发布于 2015-02-16 14:09:09
getEntry()从来不是HashMap类的公共API的一部分。看起来它在Java 8中已经被更改了,这就是为什么您应该只依赖已发布的类的公共API。
发布于 2015-02-16 14:11:54
正在搜索的方法是final,而不是public。在Java8中,它已经被替换/删除,并且由于不是public,所以它没有被签名为deprecated,而是刚刚被删除。
/**
* Returns the entry associated with the specified key in the
* HashMap. Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}为什么您或者是谁使用反射来获取private方法来从HashMap中获取元素?而是使用简单和公共的get(key)方法。
https://stackoverflow.com/questions/28543192
复制相似问题