How to overloading method with generic parameter in java?
Say I have following class
import java.util.List;
public class C {
public void foo(List a){
}
public void foo(List b){
}
}
This gives compilation error and rightly so as erasure is doing it's job and removing the type information, so after compilation both the methods will have same parameter of list only.
If I don't want to use
public void foo(List a){
}
Is there any other way to overload the method foo()?
解决方案
Two approaches that you should follow.
Change the method names.
Use an Interface for this purpose.
then either put the foo code in the objects themselves, or use
double-dispatch (depending on your design paradigm and taste).
With code in objects that would be:
public interface FooInterface{
void foo();
}
public class Foo
{
public void abc(Collection objects)
{
for(T object: objects)
{
object.foo();
}
}
}
public class FooString implements FooInterface {
public void foo(){
// do foo for String
}
}
public class FooInteger implements FooInterface {
public void foo(){
// do foo for Integer
}
}
If Domain contains your logic.
With a double dispatch, you would pass the "FooInterface" to the foo method, and on the handler call the appropriate method depending on the type.