Reputation: 155
for example :
public static String s(Object o)
return o;
this method doesn't work/compile. To solve it I can write return o.toString()
but I don't want that. I want to change the apparent type of o which is Object to the real type of o which is I know it is String.
How can I do that? I know there is a command that I can use it but I forget it. Anyone know it?
Thank you
Upvotes: 0
Views: 205
Reputation: 68935
If you know that Object
is in fact a String
then you can simply typecast.
public static String s(Object o)
{
return (String)o;
}
Upvotes: 1
Reputation: 1500665
It sounds like you're just after a cast:
public static String castToString(Object o) {
return (String) o;
}
This will throw a ClassCastException
if o
is a non-null reference to a non-String type. (If o
is a null reference, the cast will succeed and the result will still be a null reference.)
See JLS section 5.5 for more details.
Upvotes: 2
Reputation: 39733
You can cast your Object to String:
public static String castToString(Object o) {
return (String) o;
}
Upvotes: 1