使用Java 8 update101时,HashMap.entries无法强制转换为Collection [英] With Java 8 update101 HashMap.entries cannot be cast to Collection
本文介绍了使用Java 8 update101时,HashMap.entries无法强制转换为Collection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
更新到Java 8更新101后,我在以下代码中遇到异常。它与Java 8更新91一起工作正常。
After updating to Java 8 update 101, I am getting exception in following code. It was working fine with Java 8 update 91.
访问密钥库:
KeyStore ks = KeyStore.getInstance("WINDOWS-MY");
ks.load(null, null);
Field field = ks.getClass().getDeclaredField("keyStoreSpi");
field.setAccessible(true);
KeyStoreSpi kss = (KeyStoreSpi) field.get(ks);
Collection entries;
field = kss.getClass().getEnclosingClass().getDeclaredField("entries");
field.setAccessible(true);
// This is where the exception happens
entries = (Collection) field.get(kss);
// I then have to loop on these entries, something like this:
for (Object entry : entries) { //code }
类型转换,抛出异常:
java.util.HashMap cannot be cast to java.util.Collection
最近的任何更改Java 8更新101?如何解决?
Any recent changes in Java 8 update 101? How to solve it?
推荐答案
我确认使用以下代码作为测试代码不起作用
I confirm it does not work using the following as test code
import java.util.HashMap;
import java.util.Collection;
public class HelloWorld {
public static void main(String[] args) {
HashMap map = new HashMap();
Collection c;
c = (Collection) map;
}
}
结果是线程中的异常main java.lang.ClassCastException:java.util.HashMap无法在HelloWorld.main(HelloWorld.java:8)上转换为java.util.Collection
您可以使用像这样的values()方法覆盖它
You can override it by using the values() method like this
import java.util.HashMap;
import java.util.Collection;
public class HelloWorld {
public static void main(String[] args) {
HashMap map = new HashMap();
Collection c;
c = map.values();
}
}
所以你的代码应该是这样的
So your code should be like this
import java.util.HashMap;
import java.util.Collection;
import java.security.*;
import java.lang.reflect.Field;
public class HelloWorld {
public static void main(String[] args) {
try{
KeyStore ks = KeyStore.getInstance("WINDOWS-MY");
ks.load(null, null);
Field field = ks.getClass().getDeclaredField("keyStoreSpi");
field.setAccessible(true);
KeyStoreSpi kss = (KeyStoreSpi) field.get(ks);
Collection entries;
field =kss.getClass().getEnclosingClass().getDeclaredField("entries");
field.setAccessible(true);
entries = ((HashMap) field.get(kss)).values();
}catch(Exception e){
e.printStackTrace();
}
}
}
这篇关于使用Java 8 update101时,HashMap.entries无法强制转换为Collection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文