szidijani
szidijani

Reputation: 1014

How to cast dynamically in java with the usual brackets?

Or is it even possible? I'm writing a REST client at the time. There is the URLConnection class in java which is extended by HttpURLConnection and HttpsURLConnection. What I'd like is declare a type (HttpURLConnection or HttpsURLConnection) and cast this URLConnection object based on a boolean value to that declared type. F.e:

Class<? extends URLConnection> theClass = _SSL ? 
    HttpsURLConnection.class : HttpURLConnection.class;

then

((theClass) HttpConnection).setRequestMethod("POST");

or something similar.

Thanks in advance!

Upvotes: 1

Views: 336

Answers (2)

Anurag Tripathi
Anurag Tripathi

Reputation: 1208

You can do something like this.

if(_SSL) {
    ((HttpsURLConnection) HttpConnection).setRequestMethod("POST");
} else {
    ((HttpURLConnection) HttpConnection).setRequestMethod("POST");
}

As szidijani commented, there is no need of Class object.

Upvotes: 0

Remi878
Remi878

Reputation: 341

I think, you only need to cast to java.net.HttpURLConnection because your HttpsURLConnection and HttpURLConnection both extend this abstract class.

Upvotes: 2

Related Questions