Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use struct-like constructs in Java?

Tags:

java

struct

I'm considering using Java for a large project but I haven't been able to find anything that remotely represented structures in Java. I need to be able to convert network packets to structures/classes that can be used in the application.

I know that it is possible to use RandomAccessFile but this way is NOT acceptable. So I'm curious if it is possible to "cast" a set of bytes to a structure like I could do in C. If this is not possible then I cannot use Java.

So the question I'm asking is if it is possible to cast aligned data to a class without any extra effort beyond specifying the alignment and data types?

like image 950
Kristina Brooks Avatar asked Jul 31 '11 19:07

Kristina Brooks


2 Answers

No. You cannot cast a array of bytes to a class object.

That being said, you can use a java.nio.Buffer and easily extract the fields you need to an object like this:

class Packet {

    private final int type;
    private final float data1;
    private final short data2;

    public Packet(byte[] bytes) {
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        bb.order(ByteOrder.BIG_ENDIAN); // or LITTLE_ENDIAN

        type = bb.getInt();
        data1 = bb.getFloat();
        data2 = bb.getShort();
    }
}
like image 105
dacwe Avatar answered Sep 18 '22 13:09

dacwe


You're basically asking whether you can use a C-specific solution to a problem in another language. The answer is, predictably, 'no'.

However, it is perfectly possible to construct a class that takes a set of bytes in its constructor and constructs an appropriate instance.

class Foo {

  int someField;
  String anotherField;

  public Foo(byte[] bytes) {
    someField = someFieldFromBytes(bytes);
    anotherField = anotherFieldFromBytes(bytes);
    etc.
 }
}

You can ensure there is a one-to-one mapping of class instances to byte arrays. Add a toBytes() method to serialize an instance into bytes.

like image 38
Confusion Avatar answered Sep 17 '22 13:09

Confusion