1

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.

Korben
  • 734
  • 1
  • 7
  • 26
  • 3
    `m((String)s); ` or `m(s.toString())` if you want this to work for all reference types. – Eran Jun 06 '18 at 07:52
  • 1
    instead of final Serializable s = "hello world"; use final String s = "hello world"; ot cast the param – Dmitri Gudkov Jun 06 '18 at 07:53
  • @Eran I can't do explicit casting since there are other variables like Integer.. etc – Korben Jun 06 '18 at 07:53
  • 2
    Possible duplicate of [Overloaded method selection based on the parameter's real type](https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type) – Ryan Leach Jun 06 '18 at 07:54

3 Answers3

4

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).

Daniele
  • 2,672
  • 1
  • 14
  • 20
1

Try this:

if (s instanceof String)
  m((String)s);
else
  m(s);
Robert Kock
  • 5,795
  • 1
  • 12
  • 20
0

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);
BUY
  • 705
  • 1
  • 11
  • 30