Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Why am I getting a ClassCastException when the class is clearly of the right type?

0
Posted

Why am I getting a ClassCastException when the class is clearly of the right type?

0

Q: I am getting an exception when I run my module, such as java.lang.ClassCastException: Implementation cannot be cast to Interface at Factory.newInstance (Factory.java:123) But Implementation implements Interface, so why is this a CCE? A: Usually this is because the Interface that Implementation actually implements was loaded from a different class loader than what Factory sees. That is very likely the immediate cause of the CCE. The root cause is not always obvious, but it is likely to be that some code uses Thread.currentThread().getContextClassLoader() to load a class by name. In NB by default the context class loader just looks around in loaded modules (lacking any better information), so it is possible for the following situation to arise: module A: Interface, Factory module B > A: Implementation implements Interface module C: Interface, Factory module D > A: Implementation implements Interface where Factory does something like: Interface i = (Interface) Class.forName(“Implementa

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123