Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why InputStream and OutputStream implement Closeable and Socket doesn't?

Tags:

java

interface

Have seen this comment in a method:

//I wonder why Sun made input and output streams implement Closeable and left Socket behind

It would prevent creation of wrapper anonymous inner class which implements Closeable which delegates its close method to an instance of Socket.

like image 436
Boris Pavlović Avatar asked Jul 20 '09 11:07

Boris Pavlović


1 Answers

Closeable was introduced in Java5 whereas Socket was introduced in JDK 1.0. In Java7 Socket will be Closeable.

EDIT

You can use reflection in order to close any "closeable" object in Java 4/5/6 simply by testing the presence of a close method. Using this technique allow you to close, say, a ResultSet (that has a close() method but doesn't implements Closeable):

public static universalClose(Object o) {
    try {
        o.getClass().getMethod("close", null).invoke(o, null);
    } catch (Exception e) {
        throw new IllegalArgumentException("missing close() method");
    }   
}
like image 153
dfa Avatar answered Sep 16 '22 12:09

dfa