Return Java 中的对象[]

Return Object[] in Java

我需要 return 整数和字节数组,我发现我可以 return 使用 Object[],但我不确定如何获得整数和字节数组。

它 returns 具有整数和字节数组的对象:

public static Object[] readVarInt(DataInputStream in) throws IOException {
    int i = 0;
    int j = 0;
    byte[] byteArr = null;
    byte b = 0;
    while (true) {
        int k = in.readByte();
        i |= (k & 0x7F) << j++ * 7;
        if (j > 5) {
            throw new RuntimeException("VarInt too big");
        }
        if ((k & 0x80) != 128) {
            break;
        }
        byteArr = Arrays.copyOf(byteArr, b);
        byteArr[b] = (byte) k;
        b+=1;
    }
    return new Object[] {i, byteArr}; // <<---
}

我不知道如何从 Object[] 中获取我的整数和字节数组:

Object Object;
Object = Protocol.readVarInt(serv_input);
int intLength = Object[0]; // <<---
byte[] byteArray = Object[1]; // <<---

这行不通因为它认为它是数组,但它是对象...

(对不起,我知识匮乏,我是 Java 的新人...)

您可以做的是使用 instanceof 测试您尝试访问的对象是否属于特定的 class,然后显式转换您的对象。

if (test[0] instanceof Integer) {
  intLength = (Integer) test[0];
} 
if (test[0] instanceof byte[]) {
  byteArray = (byte[]) test[0];
}

但是我不建议这样做,因为我倾向于不将东西存储在对象中,因为你永远不知道它们是哪个 class。

也许您应该尝试将数据存储在一个 Map 中,该 Map 以您正在计算的长度作为键,以字节数组作为值。

Map<Integer, byte[]> result = new HashMap<>();
result.put(i, byteArray);

需要注意的一点是,映射的键不能是整数,而是整数。

您可以使用类型转换从 Object[]

获取数据
    int intLength = (int) result[0];
    byte[] byteArray = (byte[]) result[1];

但我建议使用包装器对象而不是 Object[] 作为方法的结果:

class Result {
    private final int length;
    private final byte[] byteArr;

    Result(int length, byte[] byteArr) {
        this.length = length;
        this.byteArr = byteArr;
    }

    public int getLength() {
        return length;
    }

    public byte[] getByteArr() {
        return byteArr;
    }
}

public static Result  readVarInt(DataInputStream in) throws IOException {
    ...
    return new Result(i, byteArr);
}

....

Result result = readVarInt(serv_input);

int intLength = result.getLength();
byte[] byteArray = result.getByteArr();

另请注意,这部分 byteArr = Arrays.copyOf(byteArr, b); returns NPE 在执行的第一步中,因为您正试图从 null 复制数据。