Search code examples
javaandroidclassloader

Correct use of Classloader (especially in Android)


I read some documentations about classloaders, but im still not sure where and why they are needed. The Android API says:

Loads classes and resources from a repository. One or more class loaders are installed at runtime. These are consulted whenever the runtime system needs a specific class that is not yet available in-memory.

So if i understand this correct, there can be many classlaoders which are responsible for loading new classes. But how the system decides which to use? And in which situation should a developer instantiate a new classloader?

In the Android API for Intent there is a method

public void  setExtrasClassLoader  (ClassLoader  loader)

The description says:

Sets the ClassLoader that will be used when unmarshalling any Parcelable values from the extras of this Intent.

So can i define there a special classloader so that i can pass object with an Intent which are not defined in the receiving activity? An example:

If activity A which is located in Project A (in Eclipse) defines an object which i want to send to Activity B in Project B using putExtra of the Intent object. If this object which is send over the Intent is not defined (source code in project B), then there is a NoClassDefFoundException. So can i use the method setExtraClassloader to avoid this exception? If yes, how can i decide which classloader object i have to pass? And how do I instantiate it correctly?


Solution

  • I read some documentations about classloaders, but im still not sure where and why they are needed.

    Generally speaking, you do not need to touch the classloader system.

    And in which situation should a developer instantiate a new classloader?

    After about a decade's experience in Java programming. :-)

    If activity A which is located in Project A (in Eclipse) defines an object which i want to send to Activity B in Project B using putExtra of the Intent object. If this object which is send over the Intent is not defined (source code in project B), then there is a NoClassDefFoundException. So can i use the method setExtraClassloader to avoid this exception?

    No, because Project A and Project B cannot share code. Put the class you need in both projects. Or use a remote service interface with AIDL instead of Intents and extras. Or do not use a custom class, but rather treat the object as a data structure (e.g., use a simple HashMap of Strings or something).