见过的方法,此评论:为什么InputStream和OutputStream实现Closeable并且Socket没有?
//I wonder why Sun made input and output streams implement Closeable and left Socket behind
这将阻止它实现了可关闭的包装匿名内部类的创建,并代理其Socket实例close方法。
见过的方法,此评论:为什么InputStream和OutputStream实现Closeable并且Socket没有?
//I wonder why Sun made input and output streams implement Closeable and left Socket behind
这将阻止它实现了可关闭的包装匿名内部类的创建,并代理其Socket实例close方法。
Closeable在Java5中引入,而Socket在JDK 1.0中引入。在Java7 Socket will be Closeable。
EDIT
可以使用反射,以便简单地通过测试方法密切的存在以关闭在Java中4/5/6任何“可封闭”对象。使用这种技术允许你关闭,也就是说,一个结果集(具有close()方法,但没有实现可关闭):
public static universalClose(Object o) {
try {
o.getClass().getMethod("close", null).invoke(o, null);
} catch (Exception e) {
throw new IllegalArgumentException("missing close() method");
}
}
我不知道,但我想在他们认为有它的NIO的SocketChannel不够好时间...
此外,插座已经存在了很长一段时间。开始将其称为Closeable而不是调用Socket.close()的新代码不会向后兼容,因此可能在1.5时(他们添加了Closeable时),他们不认为值得考虑不少用户仍然希望与1.4兼容,并且因为它没有其他通用接口,所以很少将它看作是Socket的其他任何接口。
我认为与1.4的向后兼容性不像现在这个问题那么可能是Java7中出现的原因。
“akappa”有一个恕我直言的其他有效的点。
为什么不问这个问题?相反,你引用了一条评论,评论包含了难以阅读的问题。 – Buttons840 2011-09-02 18:44:26
@ Buttons840我认为这个问题显然是在标题中提出的。正文包含说明。 – 2011-09-17 18:36:19