如何序列化ByteBuffer
我希望使用 RMI 跨网络发送 java.nio.ByteBuffer,但是 ByteBuffer 不可序列化。我已尝试以下自定义类但无济于事:
public class NetByteBuffer implements java.io.Serializable {
ByteBuffer buffer;
public NetByteBuffer(ByteBuffer buffer) {
this.buffer = buffer;
}
public ByteBuffer getByteBuffer() {
return this.buffer;
}
}
客户端仍然收到不可序列化的异常。有什么想法吗?
谢谢
I wish to send a java.nio.ByteBuffer accross a network using RMI, however ByteBuffer isn't serializable. I've tried the following custom class to no avail:
public class NetByteBuffer implements java.io.Serializable {
ByteBuffer buffer;
public NetByteBuffer(ByteBuffer buffer) {
this.buffer = buffer;
}
public ByteBuffer getByteBuffer() {
return this.buffer;
}
}
The client still gets a non-serialzable exception. Any ideas?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。您最好获取
byte[]
并将其发送,并在另一端重建ByteBuffer
。您当然会失去它作为缓冲区的优势。You can't. You'd better obtain the
byte[]
and send it instead and reconstruct theByteBuffer
on the other side. You are of course losing the advantages of it being a buffer.就像其他人所说的那样,ByteBuffer 是字节缓冲区的包装,因此如果您需要序列化您的类,最好更改为 byte[] 并在将数据读/写到该 bean 的类中使用 ByteBuffer。
但是,如果您需要序列化 ByteBuffer 属性(例如使用 Cassandra blob),您始终可以实现自定义序列化(检查此 url http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html)。
要点是:
尝试这门课程,让我知道这是否适合您:
Like others said ByteBuffer is a wrap of a buffer of bytes so if you need to serialize your class is better to change to byte[] and use ByteBuffer in the classes which are reading/writing data into this bean.
But if you need to serialize a ByteBuffer property (for example usign Cassandra blobs) you can always implement a custom serialization (check this url http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html).
The main points are:
Try this class and let me know if this works for you:
您可能需要更多地说明为什么要序列化字节缓冲区。如果您只是尝试通过网络发送一堆字节,@Bozho 的答案已经可以满足您的要求。
如果您确实想发送包含其内容和状态的 ByteBuffer,您可能需要重新考虑您的设计,或者至少在这里进行解释,以便其他人可以提供更多指导。
You probably need to say more about why you're serializing a byte buffer. If you're simply trying to send a bunch of bytes across the network, @Bozho's answer has got you covered.
If you actually want to send across a
ByteBuffer
including its contents and state, you probably need to rethink your design, or at the very least explain it here so others can provide more direction.虽然还有很长的路要走,但您的目标可以实现:
您可以创建一个实例变量类型为“ByteBuffer”的远程对象,并定义 getter 和 setter 远程方法来访问该变量。
Long way but your goal can be accomplish:
u can create a remote object with instance variable type of "ByteBuffer" and defined the getter and setter remote methods to access that variable.