I am new to generics. You can see I am repeating some code after knowing the exact type of val, filterSmall, filterGreat. I want to write generic code for comparing val against filter values. I could write something like this
private <T> boolean compareAgainstFilters(T val, T filterSmall, T filterGreat) {
if (!(filterSmall != null && filterSmall <= val)) {
return true;
}
if (!(filterGreat != null && val <= filterGreat)) {
return true;
}
return true;
}
but at compile time, java wouldn't know if the <= operator is valid for type T.
I don't want to repeat the code, so how can I achieve that?
if (value != null) {
switch (value.getClass().getName()) {
case "java.lang.Long":
Long filterSmall = (Long) filterSmaller;
Long filterGreat = (Long) filterGreater;
Long val = (Long) value;
if (!(filterSmall != null && filterSmall <= val)) {
return true;
}
if (!(filterGreat != null && val <= filterGreat)) {
return true;
}
break;
case "java.lang.Float":
Float filterSmallFloat = (Float) filterSmaller;
Float filterGreatFloat = (Float) filterGreater;
Float valFloat = (Float) value;
if (!(filterSmallFloat != null && filterSmallFloat <= valFloat)) {
return true;
}
if (!(filterGreatFloat != null && valFloat <= filterGreatFloat)) {
return true;
}
}
}
trueifvalis greater thanfilterSmall, even if it is greater thanfilterGreat. Furthermore, you returntrueifvalis smaller thanfilterGreat, even if it is smaller thanfilterSmall. Finally, I think you want toreturn false;if neitherif-clauses weretrue.switchover the class name looks odd for me. Such type checks should be avoided in general, but I see that this can be hard withNumberobjects, so if you really really have to do such tests, you should useif (value instanceof Float)...