Why am I getting a ClassCastException when the class is clearly of the right type?
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