如何避免制作ByteBuffer的防御性副本?

2022-09-02 14:03:07

我有一个类,它采用ByteBuffer作为构造函数参数。有没有办法避免制作防御性副本,以确保缓冲区不会在该点之后被修改?

ByteBuffer.isReadOnly() 不保证原始所有者不会修改缓冲区。更糟糕的是,似乎没有办法对ByteBuffer进行子类化。有什么想法吗?


答案 1

正如你所说,唯一真正的方法是,然后把它传递到构造函数中。除此之外,没有其他选择,尽管您可以将内容复制到新的,然后传递它。buf.asReadOnlyBuffer()ByteBuffer


答案 2

这是我现在能做的最好的事情:

/**
 * Helper functions for java.nio.Buffer.
 * <p/>
 * @author Gili Tzabari
 */
public final class Buffers
{
    /**
     * Returns a ByteBuffer that is identical but distinct from the original buffer.
     * <p/>
     * @param original the buffer to copy
     * @return an independent copy of original
     * @throws NullPointerException if original is null
     */
    public static ByteBuffer clone(ByteBuffer original)
    {
        Preconditions.checkNotNull(original, "original may not be null");

        ByteBuffer result = ByteBuffer.allocate(original.capacity());
        ByteBuffer source = original.duplicate();
        source.rewind();
        result.put(source);

        try
        {
            source.reset();
            result.position(source.position());
            result.mark();
        }
        catch (InvalidMarkException unused)
        {
            // Mark is unset, ignore.
        }
        result.position(original.position());
        result.limit(original.limit());
        return result;
    }

    /**
     * Returns an array representation of a buffer. The returned buffer may, or may not, be tied to
     * the underlying buffer's contents (so it should not be modified).
     * <p/>
     * @param buffer the buffer
     * @return the remaining bytes
     */
    public static byte[] toArray(ByteBuffer buffer)
    {
        if (buffer.hasArray() && !buffer.isReadOnly() && buffer.position() == 0
            && buffer.remaining() == buffer.limit())
        {
            return buffer.array();
        }
        ByteBuffer copy = buffer.duplicate();
        byte[] result = new byte[copy.remaining()];
        copy.get(result);
        return result;
    }

    /**
     * Prevent construction.
     */
    private Buffers()
    {
    }
}

我还向Oracle提交了功能请求:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7130631