URL是典型的bridge设计模式
URL构造函数完成的工作
URL(String protocol, String host, String file)
URL(String protocol, String host, int port, String file)
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
- 初始化属性protocol, host, port, authority, path, query, file, ref
authority = host + ":" + port
file = path + "?" + query
- 装配URLStreamHandler
URL(String spec)
URL(URL context, String spec)
URL(URL context, String spec, URLStreamHandler handler)
- 初始化属性protocol, authority, userInfo, host, port, file, path, query, ref.
protocol, authority, userInfo, host, port, file, path属性从context复制 - 装配URLStreamHandler,
使用handler来解析spec
静态工厂方法getURLStreamHandler(String protocol)
目的:创建URLStreamHandler
过程:
- 先从缓存里找,如果缓存里没有
- 如果URLStreamHandlerFactory存在,使用其工厂方法createURLStreamHandler(String protocol)创建,否则
- 读取java.protocol.handler.pkgs属性
The property which specifies the package prefix list to be scanned for protocol handlers
packagePrefixList += "sun.net.www.protocol"
- 遍历packagePrefixList,寻找packagePrefix + "." + protocol + ".Handler"类,
使用反射创建URLStreamHandler实例 - 将URLStreamHandler实例放入缓存
- 返回URLStreamHandler实例
JDK内置的URLStreamHandler
sun.net.www.protocol.file.Handler
sun.net.www.protocol.ftp.Handler
sun.net.www.protocol.http.Handler
sun.net.www.protocol.https.Handler
sun.net.www.protocol.jar.Handler
sun.net.www.protocol.mailto.Handler
sun.net.www.protocol.netdoc.Handler