关于HttpURLConnection的一个疑问解析

关于下段语句:
URLConnection conn = url.openConnection();
url.openConnection();返回的是URLConnection类型的对象,而URLConnection类是个抽象类。
我的重点疑惑点是:我理解的抽象类未经子类覆盖其抽象方法之前,是不能new对象,也不能实例化的,这句通过openConnection()方法返回的不是实例化的URLConnection对象么?这个代码是具体是怎么实现的?我的理解上哪里有误区?
求详细指点~ 谢谢了感激不尽。

网上的一个问题,看的时候也是产生了一些疑惑,于是去扒了一下HttpURLConnection的源码,先看一下openConnection
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}
可见调用的是一个handler的openConnection方法的返回值。handler声明为
transient URLStreamHandler handler;
然后我们看URLStreamHandler的openConnection方法
abstract protected URLConnection openConnection(URL u) throws IOException;
是一个抽象方法,其具体实现为(多个handler类我们找到其中针对http协议的实现)
com.sun.net.www.protocol.https.Handler
在该Handler类中方法openConnection代码如下:
protected URLConnection openConnection(URL var1, Proxy var2) throws IOException {
return new HttpsURLConnectionImpl(var1, var2, this);
}
这里return了一个HttpsURLConnectionImpl那么这个类继承关系如下:
HttpsURLConnectionImpl extends HttpsURLConnection extends HttpURLConnection

因此我们常用的
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();返回的实际对象为HttpURLConnectionImpl

注:handler还有一个实现
com.sun.net.ssl.internal.www.protocol.https.Handler返回的是
HttpsURLConnectionOldImpl,这里未做分析,但代码调用流程基本一致。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值