-1

我有一个字节数组,它必须转换为 MappedByteBuffer。

但是当我尝试创建 MappedByteBuffer 时,会发生错误。

error: cannot find symbol method MappedByteBuffer(int,int,int,int,byte[],int)

MappedByteBuffer.java

package java.nio;

import java.io.FileDescriptor;
import sun.misc.Unsafe;

public abstract class MappedByteBuffer
    extends ByteBuffer
{

   ...

// Android-added: Additional constructor for use by Android's DirectByteBuffer.
    MappedByteBuffer(int mark, int pos, int lim, int cap, byte[] buf, int offset) {
        super(mark, pos, lim, cap, buf, offset);  // <- when I hover mouse here, ByteBuffer() in ByteBuffer cannot be applied to message appears with a red underline.
        this.fd = null;
    }

   ...

}

字节缓冲区.java

package java.nio;
import libcore.io.Memory;
import dalvik.annotation.codegen.CovariantReturnType;

public abstract class ByteBuffer
    extends Buffer
    implements Comparable<ByteBuffer>
{

    // These fields are declared here rather than in Heap-X-Buffer in order to
    // reduce the number of virtual method invocations needed to access these
    // values, which is especially costly when coding small buffers.
    //
    final byte[] hb;                  // Non-null only for heap buffers
    final int offset;
    boolean isReadOnly;                 // Valid only for heap buffers

    // Creates a new buffer with the given mark, position, limit, capacity,
    // backing array, and array offset
    //
    ByteBuffer(int mark, int pos, int lim, int cap,   // package-private
                 byte[] hb, int offset)
    {
        // Android-added: elementSizeShift parameter (log2 of element size).
        super(mark, pos, lim, cap, 0 /* elementSizeShift */);
        this.hb = hb;
        this.offset = offset;
    }

    ...

}

我觉得奇怪的是当extends ByteBuffer在 MappedByteBuffer.java 中定义 goto 时,它显示的是 ByteBuffer.annotated.java,而不是 ByteBuffer.java

ByteBuffer.annotated.java


// -- This file was mechanically generated: Do not edit! -- //


package java.nio;


@SuppressWarnings({"unchecked", "deprecation", "all"})
public abstract class ByteBuffer extends java.nio.Buffer implements java.lang.Comparable<java.nio.ByteBuffer> {

ByteBuffer(int mark, int pos, int lim, int cap) { super(0, 0, 0, 0, 0); throw new RuntimeException("Stub!"); }

我不知道 {classname}.annotated.java 做了什么,所以它可能不是错误,但我粘贴了,因为我认为它很奇怪。

那么如何从字节数组创建 MappedByteBuffer 呢?只有 1 个构造函数,但它已损坏。

4

1 回答 1

1

只有 1 个构造函数,但它已损坏

该构造函数不是公共的(它是包私有的),所以你不能调用它。

那么如何从字节数组创建 MappedByteBuffer 呢?

你不能,而不是先将它写入文件。从文档

一个直接字节缓冲区,其内容是文件的内存映射区域。

如果您确实需要从字节数组中创建一个MappedByteBuffer专门的而不是仅仅创建一个ByteBuffer,您需要将它写入一个文件并使用FileChannel.map. 如果你只需要一个ByteBuffer,你可以使用ByteBuffer.wrap

于 2020-02-26T03:00:37.400 回答