Ars
Ars

Reputation: 639

Overloading method with generic parameters

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' ?

Upvotes: 1

Views: 63

Answers (1)

Stephan Hogenboom
Stephan Hogenboom

Reputation: 1573

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

Upvotes: 1

Related Questions