Implementing a Closeable Socket/Serversocket
To minimize boilerplate code, I'd like to have a Socket and ServerSocket class which both implement the Closeable interface.
I've seen that in Java 7, Socket and ServerSocket are likely to implement Closeable, so can't I just do something like:
public class ClosableSocket ex开发者_C百科tends Socket implements Closeable {}
and implement the needed constructors? Or are there better solutions? What I want is to use it in conjunction with Apache Commons IO IOUtil.closeQuietly(Closeable closeable)
.
I would have something like
public static void closeQuietly(Object object) {
try {
if (object instanceof Closeable)
((Closeable)object).close();
else if (object instanceof Socket)
((Socket)object).close();
else if (object instanceof ServerSocket)
((ServerSocket)object).close();
else
// use reflections to call close() if you must.
} catch (IOException ignored) {
// ignored
}
}
精彩评论