我有一个 Java 类,例如:
class Foo implements IBar
{
// Methods ..
// A bunch of fields of primitive types (int, String)
int f1;
int f2;
String f3;
// ...
}
我想把这些字段都打包到字节数组中(不要问我为什么,这个限制是C++端给我发送这种格式的数据时引入的)
我发现的唯一方法是使用 ByteBuffer
。但这是我能想到的最糟糕的情况。代码如下:
ByteBuffer buf = ByteBuffer.allocate(4);
int offset = 0;
buf.putInt(f1);
System.arraycopy(buf.array(), 0, rawHeader, offset, 4);
offset += 4;
// A bunch of lines here (pack all other fields)
有谁知道更合适的方法吗?谢谢。
最佳答案
使用 DataOutputStream
包裹 ByteArrayOutputStream
。
或者,如果您愿意,让您的类实现 Serializable
并使用 ObjectOutputStream
包装 ByteArrayOutputStream
。这当然会使字节数组只能由 Java 读取。
关于java - 将所有类的字段序列化为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13881532/