public InputStream getInputStream() throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (!isConnected())
throw new SocketException("Socket is not connected");
if (isInputShutdown())
throw new SocketException("Socket input is shutdown");
final Socket s = this;
InputStream is = null;
try {
is = AccessController.doPrivileged(
new PrivilegedExceptionAction<InputStream>() {
public InputStream run() throws IOException {
return impl.getInputStream();
}
});
} catch (java.security.PrivilegedActionException e) {
throw (IOException) e.getException();
}
return is;
}
如上一段代码,这段代码是java官方api源代码,有个问题不太明白, 为什么 调用getInputStream() 可以返回输入流的对象呢?
任何一个类要想成为对象 不是要new吗,为什么这个方法内部看不到如何new,但是调用getInputStream()这个方法就能得到输入流对象的呢?求高手告知下,感激不尽。
一步步点进去就知道了。
is = AccessController.doPrivileged(
new PrivilegedExceptionAction<InputStream>() {
public InputStream run() throws IOException {
return impl.getInputStream();
}
明显用到代理了,看Socket的构造方法,有个setImpl,会发现impl=new SocksSocketImpl(),点进去SocksSocketImpl类,发现一个继承关系,SocksSocketImpl继承PlainSocketImpl,继续PlainSocketImpl继承AbstractPlainSocketImpl类,在AbstractPlainSocketImpl类中发现getInputStream()方法,有一句话socketInputStream = new SocketInputStream();
所以在socket中调用impl.getInputStream()其实就是调用父类的父类的方法。
我也是最近才学会看源码,希望对你有帮助
这个排版(脑壳疼
– sang_Mu 5年前