就像其他人所说的 ByteBuffer 是字节缓冲区的包装,因此如果您需要序列化您的类,最好更改为 byte[] 并在将数据读/写到此 bean 的类中使用 ByteBuffer。
但是,如果您需要序列化 ByteBuffer 属性(例如使用 Cassandra blobs),您始终可以实现自定义序列化(查看此网址http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html)。
要点是:
- 将 ByteBuffer 标记为瞬态(因此默认情况下不序列化)
- 实现您自己的序列化读/写,其中 ByteBuffer --> byte[] 在序列化时和 byte[] --> ByteBuffer 在反序列化时。
试试这门课,让我知道这是否适合你:
public class NetByteBuffer implements java.io.Serializable {
private static final long serialVersionUID = -2831273345165209113L;
//serializable property
String anotherProperty;
// mark as transient so this is not serialized by default
transient ByteBuffer data;
public NetByteBuffer(String anotherProperty, ByteBuffer data) {
this.data = data;
this.anotherProperty = anotherProperty;
}
public ByteBuffer getData() {
return this.data;
}
private void writeObject(ObjectOutputStream out) throws IOException {
// write default properties
out.defaultWriteObject();
// write buffer capacity and data
out.writeInt(data.capacity());
out.write(data.array());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
//read default properties
in.defaultReadObject();
//read buffer data and wrap with ByteBuffer
int bufferSize = in.readInt();
byte[] buffer = new byte[bufferSize];
in.read(buffer, 0, bufferSize);
this.data = ByteBuffer.wrap(buffer, 0, bufferSize);
}
public String getAnotherProperty() {
return anotherProperty;
}
}