By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,034 Members | 820 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,034 IT Pros & Developers. It's quick & easy.

Copy an Object from one ClassLoader to Another??

P: n/a
I have an Object that was created in a custom class loader. Since a
Class is defined as the class name plus the class loader, a Class from
one ClassLoader is not equivalent to a Class from another ClassLoader.
For example:

Class c1 = getClass().getClassLoader().loadClass( "com.acme.FooBar" );
Class c2 = CustomClassLoader.loadClass( "com.acme.FooBar" );
FooBar newC2 = (FooBar)c2; // This throws ClassCastException!

You can not cast c2 to FooBar because the FooBar class loaded by the
system ClassLoader is not equivalent to the FooBar class that created
c2.

I've worked around this problem by serializing my c2 object into a
byte array, then deserializing my byte array back into an Object.
This has the effect of recreating the c2 object in system class
loader.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( c2 );

ByteArrayInputStream bais = new ByteArrayInputStream(
baos.toByteArray() );
ObjectInputStream ois = new ObjectInputStream( bais );
FooBar newC2 = (FooBar) ois.readObject();

It's a bit of a hack, but it works. The only caveat is that FooBar
must be Serializable. Now, how do I get the object created by
CustomClassLoader into my system class loader??? I've found one
method, but I'm looking for other suggestions (hopefully better than
mine).

-- John
Jul 17 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"John Davison" <jd******@my-deja.com> wrote in message
news:67**************************@posting.google.c om...
I have an Object that was created in a custom class loader. Since a
Class is defined as the class name plus the class loader, a Class from
one ClassLoader is not equivalent to a Class from another ClassLoader.
For example:

Class c1 = getClass().getClassLoader().loadClass( "com.acme.FooBar" );
Class c2 = CustomClassLoader.loadClass( "com.acme.FooBar" );
FooBar newC2 = (FooBar)c2; // This throws ClassCastException!

You can not cast c2 to FooBar because the FooBar class loaded by the
system ClassLoader is not equivalent to the FooBar class that created
c2.


I think you left a call to newInstance() out. You cannot cast c2 to newC2
because c2 is an instance of Class and FooBar is not derived from it. I
just wanted to make sure that nobody gets confused.

--
David Hilsee
Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.