1. 程式人生 > >java URL的建構函式說明

java URL的建構函式說明

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)

  1. 初始化屬性protocol, host, port, authority, path, query, file, ref
    authority = host + ":" + port
    file = path + "?" + query
  2. 裝配URLStreamHandler

URL(String spec)
URL(URL context, String spec)
URL(URL context, String spec, URLStreamHandler handler)

  1. 初始化屬性protocol, authority, userInfo, host, port, file, path, query, ref. 
    protocol, authority, userInfo, host, port, file, path屬性從context複製
  2. 裝配URLStreamHandler, 
    使用handler來解析spec

靜態工廠方法getURLStreamHandler(String protocol)

目的:建立URLStreamHandler

過程:

  1. 先從快取裡找,如果快取裡沒有
  2. 如果URLStreamHandlerFactory存在,使用其工廠方法createURLStreamHandler(String protocol)建立,否則
  3. 讀取java.protocol.handler.pkgs屬性
    The property which specifies the package prefix list to be scanned for protocol handlers
    packagePrefixList += "sun.net.www.protocol"
  4. 遍歷packagePrefixList,尋找packagePrefix + "." + protocol + ".Handler"類,
    使用反射建立URLStreamHandler例項
  5. 將URLStreamHandler例項放入快取
  6. 返回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