Throw exception instead of return. What is the actual type of method return?

91 views Asked by At

I was digging behind the openStream() method from URL class in Java to find its actual type of return. From OpenJDK, its source is:

public final InputStream openStream() throws java.io.IOException {
    return openConnection().getInputStream();
}

The return type is obviously an Object of InputStream which is an abstract class. So, this is the declared type, what is the actual type of return object? I followed openConnection() method which returns an object of URLConnection class. I also followed its source code to find the return of getInputSteam(). Finally, I found this code:

public InputStream getInputStream() throws IOException {
    throw new UnknownServiceException("protocol doesn't support input");
}

My question is what is the actual return type of getInputStream() which will be the actual return type of openStream()?

2

There are 2 answers

0
Reilas On BEST ANSWER

"... My question is what is the actual return type of getInputStream() which will be the actual return type of openStream()?"

Here is an example using an HTTPS address.

Use a debugging process, and place a break-point on the URL#openStream method.
And, I mean the actual method, and not your invocation.

From here, "step into" the openConnection method.
And then again, "step into" the openConnection(URL) method.

This brings you to the sun.net.www.protocol.https.Handler class.

Advance once more, to the openConnection(URL, Proxy) method, which returns a new instance of sun.net.www.protocol.https.HttpsURLConnectionImpl.

Traversing further, you'll find that an instance of HttpsURLConnection is returned, via the sun.net.www.protocol.https.DelegateHttpsURLConnection class.

0
ControlAltDel On

You know, I had (almost) this exact question when I was starting with Java years ago, except I was confused about java.awt.Graphics.

See Programming to an interface

The idea is that you actually don't need to know the precise class - anything that implements the interface can be swapped in or out. This makes code more adaptable over time.