6

我希望使用 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;
}

}

客户端仍然得到一个不可序列化的异常。有任何想法吗?

谢谢

4

4 回答 4

7

你不能。您最好获取byte[]并发送它,然后ByteBuffer在另一侧重建。您当然会失去它作为缓冲区的优势。

于 2010-10-20T22:15:25.147 回答
4

就像其他人所说的 ByteBuffer 是字节缓冲区的包装,因此如果您需要序列化您的类,最好更改为 byte[] 并在将数据读/写到此 bean 的类中使用 ByteBuffer。

但是,如果您需要序列化 ​​ByteBuffer 属性(例如使用 Cassandra blobs),您始终可以实现自定义序列化(查看此网址http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html)。

要点是:

  1. 将 ByteBuffer 标记为瞬态(因此默认情况下不序列化)
  2. 实现您自己的序列化读/写,其中 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;
    }

}
于 2015-11-04T11:00:29.773 回答
1

您可能需要详细说明为什么要序列化字节缓冲区。如果您只是想通过网络发送一堆字节,@Bozho 的回答已经涵盖了您。

如果您真的想发送ByteBuffer包含其内容和状态的内容,您可能需要重新考虑您的设计,或者至少在这里解释一下,以便其他人可以提供更多指导。

于 2010-10-21T00:53:59.740 回答
-1

很长的路要走,但你的目标可以实现:

您可以创建一个实例变量类型为“ByteBuffer”的远程对象,并定义 getter 和 setter 远程方法来访问该变量。

于 2010-10-21T01:02:57.880 回答