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
-
A way around this issue is to have the generic method more complicated, having it delegate work based on the type of the parameter.Roy Shahaf– Roy Shahaf2018年11月30日 13:23:12 +00:00Commented Nov 30, 2018 at 13:23
1 Answer 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
Ars
No. It won't work. Compiler will say "i have two exact same methods and don't know wich one to use"
Stephan Hogenboom
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?
lang-java