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

前端 未结 8 1959
时光取名叫无心
时光取名叫无心 2020-12-30 11:15

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

8条回答
  •  春和景丽
    2020-12-30 12:01

    No, you cannot do that. Java simply doesn't have the same concepts as C.

    You can create a class that behaves much like a struct:

    public class Structure {
        public int field1;
        public String field2;
    }
    

    and you can have a constructor that takes an array or bytes or a DataInput to read the bytes:

    public class Structure {
        ...
        public Structure(byte[] data) {
            this(new DataInputStream(new ByteArrayInputStream(data)));
        }
    
        public Structure(DataInput in) {
            field1 = in.readInt();
            field2 = in.readUTF();
        }
    }
    

    then read bytes off the wire and pump them into Structures:

    byte[] bytes = network.read();
    DataInputStream stream = new DataInputStream(new ByteArrayInputStream(bytes));
    Structure structure1 = new Structure(stream);
    Structure structure2 = new Structure(stream);
    ...
    

    It's not as concise as C but it's pretty close. Note that the DataInput interface cleanly removes any mucking around with endianness on your behalf, so that's definitely a benefit over C.

提交回复
热议问题