从局部变量创建 ByteArrayInputStream 是否有效?

Is it valid to create a ByteArrayInputStream from a local variable?

假设函数如下:

InputStream func() {            
       byte[] buffer = new byte[] {0,1,2,3};

       return new ByteArrayInputStream(buffer);
}

如果我调用该函数,垃圾收集器是否有可能删除 'buffer' 变量并且 InputStream 不再工作?

Is there a possibility that the garbage collector deletes the 'buffer' variable and the InputStream doesn't work anymore?

不,垃圾收集器不允许删除仍然被引用的对象。该对象是从 ByteArrayInputStream 对象中引用的(其内部 buf 成员引用该对象)。

如果您将看到 ByteArrayInputStream 的构造函数,您将看到以下内容

 public ByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

正如您所见,对字节数组的引用存储在 InputStream 对象中:this.buf = buf。并且 GC 不会收集具有强引用的对象。所以不用担心。