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.

4
  • 3
    m((String)s); or m(s.toString()) if you want this to work for all reference types. Commented Jun 6, 2018 at 7:52
  • 1
    instead of final Serializable s = "hello world"; use final String s = "hello world"; ot cast the param Commented Jun 6, 2018 at 7:53
  • @Eran I can't do explicit casting since there are other variables like Integer.. etc Commented Jun 6, 2018 at 7:53
  • 2
    Possible duplicate of Overloaded method selection based on the parameter's real type Commented Jun 6, 2018 at 7:54

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

A nice and clean answer, clarifying the problem. Good job.
1

Try this:

if (s instanceof String)
  m((String)s);
else
  m(s);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.