无法通过 Java 上的反射调用 HashMap 的 getEntry 8

Can't invoke HashMap's getEntry via reflection on Java 8

我有一些遗留代码(使用 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)

看起来它被替换为 getNode(),其中 returns 是 NodeMap.Entry<K,V> 的不同实现)。如果必须使用此方法,则必须更改代码。使用包私有方法存在风险。他们可以消失。

getEntry() 从来不是 HashMap class 的 public API 的一部分。看起来它在 Java 8 中被更改了。这就是为什么你应该只依赖 classes 的已发布 public API。

您要搜索的方法是 final 而不是 public。在 Java 8 中,它是 replaced/removed,因为不是 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 中获取元素?请改用简单明了的 public get(key) 方法。