dracularking 发表于 2013-2-3 11:19:56

URLConnection如何对应具体实现子类

import java.net.URL;import java.net.URLConnection;public class Test {public static void main(String[] args) {try {URL url = new URL("http://www.google.com.cn");URLConnection con = url.openConnection();con.setDoOutput(true);con.setDoInput(true);con.setReadTimeout(0);con.setConnectTimeout(0);con.connect();System.out.println("HeaderField:" + con.getHeaderField("content-type"));} catch (Exception e) {System.out.println("Exection:" + e.getMessage());}}} URLConnection 是根据各种协议交给不同的协议处理实现子类去处理的,这是典型的多态。 (火龙果@bao110908)

http:// 的 HTTP 协议交给 java.net.HttpURLConnection 的子类 sun.net.www.protocol.http.HttpURLConnection 处理
ftp:// 的 FTP 协议交给 URLConnection 的子类 sun.net.www.protocol.ftp.FtpURLConnection 处理
file:// 的 FILE 协议交给 URLConnection 的子类 sun.net.www.protocol.file.FileURLConnection 处理
https:// 的 HTTPS 协议交给 javax.net.ssl.HttpsURLConnection 的子类 sun.net.www.protocol.https.HttpsURLConnectionImpl 处理
jar:// 的交给 java.net.JarURLConnection 子类 sun.net.www.protocol.jar.JarURLConnection 处理
mailto:// 的交给 URLConnection 的子类 sun.net.www.protocol.mailto.MailToURLConnection 处理
 
 
比如HttpURLConnection的话,是在URL类的static URLStreamHandlergetURLStreamHandler(Stringprotocol)方法中确认其具体实现子类的某类型URLStreamHandler(通过反射) 再通过其openConnection方法获得
 
尝试总结:多态如何定位到实现子类,通过参数
页: [1]
查看完整版本: URLConnection如何对应具体实现子类