Trial Resource Behavior with Lockable Parameters

Is Java-7 try-with-resources required so that the lockable is assigned directly to the variable? In short, this block of code ...

    try (final ObjectInputStream ois = new ObjectInputStream(
            new ByteArrayInputStream(data))) {
        return ois.readObject();
    }

Equivalent to this block? ...

    try (final ByteArrayInputStream in = new ByteArrayInputStream(data);
         final ObjectInputStream ois = new ObjectInputStream(in)) {
        return ois.readObject();
    }

In my understanding of section 14.20.3 of the Java Language Specification , it is stated that they do not match and resources must be assigned. This would be surprising in terms of general usage, and I cannot find the documentation warning about the template.

+4
source share
2 answers

, . ObjectInputStream.close() close() ByteArrayInputStream, , .

EDIT: -, , , new BufferedInputStream(new *InputStream(...)) ObjectInputStream , , . , .

+3

, , Java , . , JavaDocs AutoCloseable:

, Closeable Closeable . , , Closeable.close, , . .

, close() , . , , .

+2

Source: https://habr.com/ru/post/1524738/


All Articles