Reputation: 25863
I'm fairly new to the JVM and ClassLoaders. I have these two classes:
public abstract class CoreModule extends Entity
public final class EventManager extends CoreModule
At the start of the program, I create an instance of EventManager
. So I understand that the JVM knows what Entity
class is and how to load it (that is, it knows what ClassLoader
to use), since EventManager
is a grand-child. But when an Entity
instance is passed by some serialization mechanism, it throws ClassNotFoundException
. I have to manually set the ClassLoader
to use (Event.class.getClassLoader()
).
How come the JVM does not know what Event
class is or how to load it if it already did it?
Upvotes: 4
Views: 1632
Reputation: 200138
Just by creating an instance of EventManager
you didn't show the JVM how to load it. In fact, you're not talking to the JVM here. You're talking to one specific classloader, and when that same classloader is not in charge at the time of deserialization, you can get an error. That's why your problem is all about what clasloader is in charge at what point.
Upvotes: 1
Reputation: 10628
Actually the JVM does not figure this out "magically". It is all based on a system class loader which will vary depending on the environment you use. Then each thread has a context ClassLoader which derives from this automatically.
The context ClassLoader you can change by using Thread.setContextClassLoader
If your serialization code should be able to resolve a class not visible from the context ClassLoader you need to set this the way you did.
Upvotes: 2