黑马程序员技术交流社区

标题: URL中openConnection的实现 [打印本页]

作者: leon_hm    时间: 2014-4-2 21:34
标题: URL中openConnection的实现
public URLConnection openConnection() throws java.io.IOException {
        return handler.openConnection(this);
}

以上是类URL中openConnection的代码。
handler是一个抽象类URLStreamHandler的变量。

从jdk API文档来看URLStreamHandler是没有子类的。
那是如何创建URLStreamHandler对象的呢?
抽象类应该不能new对象的吧。
作者: Engle    时间: 2014-4-2 22:01
handler在这里是URLStreamHandler 类的一个引用,你仔细看源码的话会发现:
static Hashtable handlers = new Hashtable();
URLStreamHandler handler = (URLStreamHandler)handlers.get(protocol);
               if (handler != null) {
                    handlers.put(protocol, handler);
                }

                if (handler == null) {
                    handler = context.handler;
                }

作者: leon_hm    时间: 2014-4-3 08:12
Engle 发表于 2014-4-2 22:01
handler在这里是URLStreamHandler 类的一个引用,你仔细看源码的话会发现:
static Hashtable handlers = n ...

那这个引用接收到的是什么对象呢?
handlers是个hashtable。
handlers.get(protocol);获取的是什么对象呢?
作者: Engle    时间: 2014-4-3 08:35
handlers是用来存储handler对象的,我这里只是贴出了源代码的一部分,你要想弄明白,你就得自己去看源码,你可以Ctrl+F去源码里搜索我恢复的这几行源码




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2