Since the type of the variable is lost in check(List<T> list) , you have two options:
1. Perform different actions by checking the type of execution
check(T element) { if (element.getClass().equals(SomeType.class)) { check((SomeType) element); } elseif (element.getClass().equals(SomeOtherType.class)) { check((SomeOtherType) element); }
This can be made a little more complicated, for example by wrapping each check in Callable and using Map<Class, Callable>
It looks like a visitor pattern.
2. Calling a virtual method for the item being checked
If the validation logic can be clicked on an object that will be verified by itself (this is not necessarily bad), you do not need to check the types:
interface Checkable { void check(); } class SomeType implements Checkable { .... } class SomeOtherType implements Checkable { .... }
Then:
public static <T extends Checkable> void check(List<T> list) { for (T element : list) { element.check(); } }
These are the only two options, any implementation should be a variation on one of these
Miserable variable
source share