ClassCastException due to class loader?

While playing with class loaders, I received the following exception:

Exception in thread "main" java.lang.ClassCastException: xxx.Singleton cannot be cast to xxx.Singleton 

Does this mean that the instance from the class loader cannot be applied to the class of another class loader?

Check out my code where I can create 3 singleton thanks to class loaders, even with "security".

 public static void main(String[] args) throws Exception { URL basePath = new URL("file:/myMavenPath/target/classes/"); Object instance = getClassInstance(Singleton.class); System.out.println(instance); // Object instance2 = getClassInstance( new URLClassLoader( new URL[]{basePath} , null ) .loadClass("my.Singleton") ); System.out.println(instance2); // Object instance3 = getClassInstance( new URLClassLoader( new URL[]{basePath} , null ) .loadClass("my.Singleton") ); System.out.println(instance3); // Only the 1st cast is ok Singleton testCast1 = (Singleton) instance; System.out.println("1st cast ok"); Singleton testCast2 = (Singleton) instance2; System.out.println("2nd cast ok"); Singleton testCast3 = (Singleton) instance3; System.out.println("3rd cast ok"); } private static Object getClassInstance(Class clazz) throws Exception { Method method = clazz.getMethod("getInstance"); method.setAccessible(true); return method.invoke(null); } class Singleton { private static final Singleton INSTANCE = new Singleton(); public static Singleton getInstance() { return INSTANCE; } private Singleton() { Exception e = new Exception(); StackTraceElement[] stackTrace = e.getStackTrace(); if (!"<clinit>".equals(stackTrace[1].getMethodName())) { throw new IllegalStateException("You shall not instanciate the Singleton twice !",e); } } public void sayHello() { System.out.println("Hello World ! " + this); } } 
+6
source share
3 answers

You cannot throw between classloaders. The class identifier consists of the fully qualified name and class loader. Check out the crysis class id here .

+3
source

Yes you are right.

This often happens in OSGi projects due to poor dependency management.

+2
source

This is exactly the case. You cannot cast between classes loaded by different class loaders.

This question, β€œDrop through the class loader,” can make everything clearer ...

+2
source

Source: https://habr.com/ru/post/922362/


All Articles