Search code examples
javaserializationclassloader

Equivalent of ObjectOutputStream, saving not only its state but the whole object?


I'm letting the user import plugin-like classes from a remote location using URLClassLoader, so these imported classes do NOT exist in the build path (however, they all implement an interface IPlugin which is included).

I assumed one could simply use ObjectOutputStream to save all the loaded plugins to file, and later read these with ObjectInputStream. That doesn't seem to be the case though, since all it saves is the state of the object, not the containing logic (i.e. methods).

What I'd hope to do is to save the list of loaded plugins (activePlugins) with ObjectOutputStream:

ObjectOutputStream oos = new ObjectOutputStream(*fileoutputstream*);
oos.writeObject(activePlugins);
oos.close();

Then at another runtime, load/restore all these plugins with ObjectInputStream:

ObjectInputStream ois = new ObjectInputStream(*fileinputstream*);
activePlugins = (ArrayList<IPlugin>) ois.readObject();

But since the actual object classes are not available in the build path (they are somewhere else on the harddrive), it goes haywire. What I'm after is some way of loading objects without having the classes available, i.e. loading objects with states and without dependencies.


Solution

  • you need your own classloader. you basically want something similar to URLClassLoader, but with the ability to download and cache the jars locally. you might want to look at extending URLClassLoader or implementing something similar to it. you basically need to just hook into the part where the jar is downloaded and stick it somewhere locally (or load it from that cached location if you already downloaded it previously).