简体   繁体   中英

Convert java class fields directly to byte array

Let me have a simple class

public class A
{
    public int a;
    public int b;
    public byte c;
    public byte  d;
    public B e;
    public C f;
    public byte[] g = new byte[5];
}

Is there a way to convert it into a byte array without doing it by hands? Same order of fields in the result array is needed and no other info in byte array is allowed, just field values.

If you like to use reflection you have no guarantees on the order of retrieved fields.

So you can use two approaches:

  • Order lexycally the fields
  • Add an annotation to each field with the order of that field in the serialization

Note that for the array serialization you have to know the length of the array or use a delimiter to denote the end of the array. In the simple case of your example this is not needed because you have only 1 array. It becomes necessary if you have more than one variable length variable (a String or an array for example).

If you need to share these data between your code and external code you have to be sure that your serialization process is equal to the serialization process of the external program. It means to know for example if an int is represented as BigEndian or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM