4

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?

5
  • Can you provide more details about infrastructure? Commented Jul 16, 2012 at 13:51
  • Sorry, but I don't know what you mean by "infrastructure". The JVM proper is Dalvik. Commented Jul 16, 2012 at 13:53
  • Is it webapplication or desktop application?are you using any frameworks? are you using any special classes for serialization etc., Commented Jul 16, 2012 at 13:56
  • @thinksteep It's hardly a webapplication/desktop application running on an Android phone. Commented Jul 16, 2012 at 13:59
  • It's a standard Android service. Commented Jul 16, 2012 at 14:09

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I understand now that when de-serialization is done, it's a system thread that does it, and thus, it doesn't know about my class.
1

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.

1 Comment

Thanks for the answer, I understand the class loading mechanism much better now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.