J
John Davison
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
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