When using java 8 update101, HashMap Entries cannot be cast to collection
•
Java
After updating to Java 8 update 101, I encountered an exception in the following code It works well with Java 8 update 91
To access the keystore:
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 }
Type conversion, exception thrown:
java.util.HashMap cannot be cast to java.util.Collection
Any recent changes in Java 8 update 101? How?
Solution
I confirm that it cannot use 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; } }
The result is an exception in the thread "main" lang.ClassCastException:java. util. HashMap cannot be cast to Java util. Collection at HelloWorld main(HelloWorld.java:8)
You can override it with a 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(); } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码