What?! java.lang.ClassCastException?!

If you are facing something very strange like com.tassioauad.MyEntity cannot be cast to com.tassioauad.MyEntity, don’t worry because you are not alone.  It’s  typically occurs when two ClassLoader load the classes with the same name, because different ClassLoader can do the same class be considered different.

What is the ClassLoader?  It is a class that load other classes, loading the bytecodes of the classes to the memory and making possible to the application use this in any of yours parts.  If it’s a class that load classes, who load it? The Bootstrap Classloader, written in a native language and loaded firstly on the JVM. We can have how many ClassLoader as we want and web containers make use of this possibility to have many ClassLoader to avoid that two or more applications load a class with the same fully qualified name. It’s great but it is our problem.

The formula of a Java class equality is: Same fully qualified name + Same the ClassLoader that loaded it. So, if the fully qualified name of the classes is the same but the ClassLoader that loaded it is different, this classes will considered different.

So, if you are facing it in your application, make sure that you are not using different class loaders to load the class, any interface that is being implemented in this class or even any subclass of this class.

prague-3010407_640
from pixabay.com

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s