1

I have method that returns generic parameter. For example

public E doSmth(E item){
return item;
}

Is there a way to create same method get but only for example String like

public String doSmth(String item){
return item + item;
}

So if i pass String, it works with String, but if i pass anything else it does basic method with generic. Can i somehow do it without error that 'two same methods in class' ?

asked Nov 30, 2018 at 13:11
1
  • A way around this issue is to have the generic method more complicated, having it delegate work based on the type of the parameter. Commented Nov 30, 2018 at 13:23

1 Answer 1

1

This should work right? Java will always try to call the method that has the most refined type of the parameter you have put in the call

public <E> E doSmth(E item){
 return item;
}
public String doSmth(String item){
 return item + item;
}
answered Nov 30, 2018 at 13:29

2 Comments

No. It won't work. Compiler will say "i have two exact same methods and don't know wich one to use"
Can you show how you call the method? I tried this multiple times and it seems to work. Do you have other method with the same signature that might conflict?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.