Milkmate
Milkmate

Reputation: 111

String can't be cast to an Integer and Integer can't be cast to a String

The getHttpPort method returns an Object type derived from a JSON data query. The value of the Object could be a blank string or an Integer value. To be on the safe side I thought I could represent it as a String like this:

String port = (String)getHttpPort(param);

But this sometimes generates the error:

Integer cannot be cast to a String.

So I tried this:

String port = ((Integer)getHttpPort(param).toString();

But now I get the reverse error:

String cannot be cast to an Integer.

What's the proper way to represent the returned result of the getHttpPort method as a String?

Upvotes: 1

Views: 139

Answers (2)

Aravind Yarram
Aravind Yarram

Reputation: 80176

toString() is present in every class in Java. So change this

String port = ((Integer)getHttpPort(param).toString();

to

String port = getHttpPort(param).toString();

Now, this will work for the scenarios where toString() is implemented .

Upvotes: 3

hvgotcodes
hvgotcodes

Reputation: 120188

Did you try

String port = getHttpPort(param).toString();

?

Upvotes: 4

Related Questions