Search code examples
javaserializationclassloader

How to send a Class over the wire


I have the following problem: I want to send a type (java.lang.Class) over the wire and 'define' the class on the other side.

I tried like that:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(MyClass.class);

and on the receiving end:

ByteArrayInputStream bis = new ByteArrayInputStream(request.getBytes());
ObjectInputStream ois = new ObjectInputStream(bis);
Class c = (Class) ois.readObject(); // ClassNotFoundException

so obviously I need to send the raw bytecode of the class and do a

ClassLoader.defineClass(bytes, ..

but unfortunately I fail to see how I can retrieve the bytcode of a loaded class. I'm searching for something like:

byte[] byteCode = MyClass.class.toByteArray();

Is this even possible with standard JDK or is there any small lib out there that can do that?


Solution

  • I don't think what you want is possible in full generality. The act of defining a class from its bytecode is not reversible. What you should be able to do, however, is to directly read the bytecode file (assuming that it's an URLClassLoader):

    MyClass.class.getResourceAsStream("Myclass.class")
    

    Alternatively, you could just make the class files accessible via HTTP and directly use an URLClassLoader on the receiving side.