As part of an exercise I had to write a remote class loader. It downloads a class from a server and then loads it using defineClass.
What I did was something like this:
in=new ObjectInputStream(s.getInputStream());
Object o = in.readObject();
return defineClass(className,o.toString().getBytes(), 0, o.toString().length());
And I got a java.lang.ClassFormatError: Incompatible magic value
But when I wrote this
in=new ObjectInputStream(s.getInputStream());
byte[] classData=(byte[])in.readObject();
return defineClass(className,classData, 0, classData.length);
It worked as expected.
Why is that?
Object.toString()string returns youhuman readable form of ObjectSo if you calltoStringonarrayobject then it will return youdefault toString.Default toString implementation is
You can clearly see this is not what you wanted.
You can use
Stringconstructor withCharsetor default charset to convertbyte[]to stringReferences: