开发者

Byte based (de)serialization in Java?

I want to try abusing Java classes as structures and for that I'm wondering if it is possible to serialize a byte array to a class and other way around.

So if I have a class like this:

public class Handshake
{
    byte command;
    byte error;
    short size;
    int major;
    int ts;
    char[] secret; // aligned size = 32 bytes
}

Is there an easy way (without having to manually read bytes and fill out the class which requires 3 times as much code) to deserialize a set of bytes into this class? I know that Java doesn't have structs but I'm wonderin开发者_C百科g if it is possible to simplify the serialization process so it does it automatically. The bytes are not from Java's serializer, they are just aligned bytes derived from C structs.


The bytes are not from Java's serializer, they are just aligned bytes derived from C structs.

Bad idea. It can break as soon as someone compiles that code on a different platform, using a different compiler or settings, etc.

Much better: use a standardized binary interface with implementations in Java and C++ like ASN.1 or Google's Protocol Buffers.


You can write a library to do the deserializtion using reflection. This may result in more code being required, but may suit your needs. It worth nothing that char in Java 16-bit rather than 8 bit and a char[] is a separate Object, unlike in C.

In short you can write a library which reads this data without touching the Handshake class. Only you can decide if this is actually easier than adding a method or two to the handshake class..


Do not do that! I will break sooner or later. Use some binary serialization format, like [Hessian][1], which supports both java and C++ (I'm not aware of anything that works on plain C)
Also remember C does not force size for int's or long's, they are platform dependent. So if you must use C, and you are forced to write your own library, be very careful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜