How to send a Class over the wire

天涯浪子 提交于 2019-12-06 14:21:42

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.

You cannot do this from memory. You must have the byte codes defining the class, which for most classes can be found by asking the JVM. This code from http://www.exampledepot.com/egs/java.lang/ClassOrigin.html should get you started:

// 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/

You should check java serialization interface

edit :

I re-read your post and you're talking about defining the class on the other side. This lead me to think that what you're trying to accomplish is to distribute objects across the network.

Also, if both your server and client share the same interface, you can simply create objects via java reflection

Peter

You could write your own serialization method.

so

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.

}

This is the method that we implement in .Net for serialization. The key thing with this method is it puts you in complete charge of serialization. It may be long winded if you're not going to have any versions of this type of communication but for multiple versions as the product grows this is one of the few reliable methods we've found to do it.

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

We use the same dll on the corporate server as we do on the client.

Serialization is an issue no matter which platform you're on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!