No, you cannot do this. Java simply does not have the same concepts as C.
You can create a class that behaves like a structure:
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 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 the bytes from the wire and transfer them to Structures :
byte[] bytes = network.read(); DataInputStream stream = new DataInputStream(new ByteArrayInputStream(bytes)); Structure structure1 = new Structure(stream); Structure structure2 = new Structure(stream); ...
It is not as concise as C, but it is pretty close. Please note that the DataInput interface cleanly removes any beats with integrity on your behalf, so there is definitely an advantage over C.
Cameron skinner
source share