简体   繁体   English

将Java类字段直接转换为字节数组

[英]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 Lexycally订购领域
  • 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. 在您的示例的简单情况下,这是不需要的,因为您只有1个数组。 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. 例如,这意味着知道一个int是否表示为BigEndian

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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