我使用Android HttpURLConnection
进行网络下载。这是我的代码:
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL("http://XXXXXXXXXX").openConnection();
InputStream inputStream = conn.getInputStream();
Log.d("Reflection",inputStream.getClass().getCanonicalName());
int TOTAL_LEN = conn.getContentLength();
byte[] buf = new byte[1024 * 8];
int len = 0, total = 0;
while (len != -1) {
len = inputStream.read(buf);
total += len;
Log.d("Download Process:", total * 1.0 / TOTAL_LEN * 100 + "");
}
}catch (Exception e) {
e.printStackTrace();
}
由于Inputstream
是一个抽象类,我使用反射来显示它的实现:inputStream.getClass().getCanonicalName()
。但结果是空的。
所以我尝试inputStream.getClass()
,结果是class com.android.okio.RealBufferedSource$1
。
为什么呢?我怎样才能在这里找出inputstream
的真实实现?
问题已解决
答案是anonymous class
。我浏览了Android源代码并发现了它。位置为/external/okhttp/okio/src/main/java/okio/RealBufferedSource.java
,代码如下:
public InputStream inputStream() {
return new InputStream() {
@Override
public int read() throws IOException {
if (closed) throw new IOException("closed");
if (buffer.size == 0) {
long count = source.read(buffer, Segment.SIZE);
if (count == -1) return -1;
}
return buffer.readByte() & 0xff;
}
@Override
public int read(byte[] data, int offset, int byteCount) throws IOException {
if (closed) throw new IOException("closed");
checkOffsetAndCount(data.length, offset, byteCount);
if (buffer.size == 0) {
long count = source.read(buffer, Segment.SIZE);
if (count == -1) return -1;
}
return buffer.read(data, offset, byteCount);
}
@Override
public int available() throws IOException {
if (closed) throw new IOException("closed");
return (int) Math.min(buffer.size, Integer.MAX_VALUE);
}
@Override
public void close() throws IOException {
RealBufferedSource.this.close();
}
@Override
public String toString() {
return RealBufferedSource.this + ".inputStream()";
}
};
}
请注意,此方法返回new InputStream()
并且它是匿名的。