Search code examples
javaurlreturn-type

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


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()?


Solution

  • "... 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.