How to send a class by cable

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

I tried like this:

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

and on the receiving side:

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

so obviously i need to send the class source bytecode and do

ClassLoader.defineClass(bytes, ..

but unfortunately I donโ€™t see how I can get the byte code of the loaded class. I am looking for something like:

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

Is this even possible using the standard JDK, or is there a small lib that can do this?

+2
source share
4 answers

, , , . - . - ( , URLClassLoader):

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

, HTTP URLClassLoader .

+5

. , , , JVM. http://www.exampledepot.com/egs/java.lang/ClassOrigin.html :

// Get the location of this class
Class cls = this.getClass();
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation();  // file:/c:/almanac14/examples/
+1

.

public byte[] Serialize()
{

// serialize each field in turn here.

return data;
}


public void Deserialize(byte[] data)
{

// deserialize data in the same order it was serialized.

}

, .Net . - . , - , , .

We use memory stream objects to write out each data field and cascade the recording of complex objects, implementing the iserializable interface (which may not exist in java, but it is a simple interface to implement independently).

We use the same DLL on the corporate server as on the client.

Serialization is a problem, no matter what platform you are on.

-3
source

All Articles