Arian Hosseinzadeh Arian Hosseinzadeh - 3 months ago 28
Java Question

Java overloading with generic type parameter

I have the following methods in one class:

void delete(ClassA a) {
//....
}

void delete(ClassB b) {
//...
}

void delete(List<ClassA> list) {
for (ClassA a: list) {
delete(a);
}
}

void delete(List<ClassB> list) {
for (ClassB b: list){
delete(b);
}
}


The overloading works fine for the first two methods. But there's a conflict between third and fourth methods.

Is it possible to replace them with one method? I tried the following method, which is not correct:

void delete(List<? extends Object> list){
for (Object o: list){
delete((o.getClass())o);
}
}


How can I detect the class type of the instance in list at runtime and call the appropriate method?

Answer Source

Overloading is resolved at compile time, so you can't rely on the runtime types.

What you can do is check the runtime types with instanceof and cast to the relevant type explicitly:

void delete(List<? extends Object> list){
    for (Object o: list) {
        if (o instanceof ClassA) {
            delete((ClassA) o);
        } else if (o instanceof ClassB) {
            delete((ClassB) o);
        }
    }
}