Reputation: 736
suppose I have a two methods defined in on class as following
public void m(final Serializable s){
System.out.println("method 1");
}
public void m(final String s){
System.out.println("method 2");
}
if I have a variable defined as
final Serializable s = "hello world";
How can I use this variable to invoke m so that "method 2" will be printed on the console? I have tried
m(s.getClass().cast(s));
but still method 1 is invoked, but the above code does cast s to String type from my observation.
Upvotes: 1
Views: 88
Reputation: 736
You can cast it to a String in several ways like:
m((String) s);
or:
m(s.toString());
Or you can initialize a String variable with s and invoke the method with it like:
String invoker = "" + s;
m(invoker);
Upvotes: 0
Reputation: 2837
Your variable s
is of type Serializable
, but in fact it points to a String
object (since the literal "hello world"
gives you an object of that type), so it can be cast to (String)
.
Overloaded method calls are resolved at compile time using the most specific type available (known at compile time); what you are doing here, is trying to resolve using the most specific type known at run-time.
In Java you could do that using the Visitor pattern, (but unfortunately you can't extend String
; you can if you declare your own types).
Upvotes: 4