0

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 wondering 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.

3
  • Maybe I'm missing something, but what exactly is the difference between this question and your previous one? Commented Aug 1, 2011 at 14:35
  • This is treading awfully close to being a duplicate of your own questions - stackoverflow.com/questions/6891663/…. Commented Aug 1, 2011 at 14:36
  • I'm still trying to find out if I can achieve this sort of thing in Java. Commented Aug 1, 2011 at 14:37

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The client's protocol is well defined and isn't going to be changed in the near future.
@Nick Brooks that implies that it must be defined some way other than via C structs.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.