Custom logic for specific bounded generic types in Java

41 Views Asked by At

I'm having the following hierarchical structure for A, B and C:

interface A {

}

class B implements A {

}

class C implements A {

}

I want to design a generic method that takes in Set of any subtype of A and perform some custom logic if the subtype is either B or C.

I've the following for code-block for the above mentioned thing:

public class Main {
    public static <T extends A> void method1(Set<T> items) {
        if (/* condition for instances of B */) {
            // some custom logic for type B
        } else if (/* condition for instances of C */) {
            // some custom logic for type C
        } else {
            throw new RuntimeException("Type not supported.");
        }
    }

    public static <T extends A> void method2(Set<T> items, Class<T> tClass) {
        if (tClass == B.class) {
            // some custom logic for B
        } else if (tClass == C.class) {
            // some custom logic for C
        } else {
            throw new RuntimeException("Type not supported.");
        }
    }
}

I want to model it in the way how method1 is modelled (without passing an extra Class<T> in the parameter list). method2 achieves that but by passing a Class<T> parameter.

What is the elegant way to achieve this?

I'm aware of type-erasure in Java (and so type T will not be available at runtime). Also, I could have extracted out the common functionality in the interface A itself and simply call item.extractedMethod() which would have avoided the if-else block.

So I just wanted to check if there's any other elegant way of handling this type of scenario.

0

There are 0 best solutions below