-1

I'm writing universal compare utility, it should be type safe as possible. Idea is to prevent comparing of different class Objects. For example this works OK:

UtilityClazz.<String>compare("dd", 1); //OK - compile time error

Is there more elegant way to call Utility class, that has type parameter. This below is not OK because it will compare Date and int

compare(SomeObject.getDate(), 1); //NOT OK - compiles OK no type is passed

Method Code:

public static<T> int compare(T value1, T value2) {
    if (value1 instanceof Time && value2 instanceof Time) {
        return DateComparator.compareTimes((Time) value1, (Time) value2);
    } else if (value1 instanceof Date && value2 instanceof Date) {
        return DateComparator.compareDates((Date) value1, (Date) value2);
    } else if (value1 instanceof Number && value2 instanceof Number) {
        return NumberUtility.compare((Number) value1, (Number) value2);
    } else {
        //....
        return 0;
    }

}

}

How to make method call elegant as possible ?

Levijatanu
  • 371
  • 2
  • 17

3 Answers3

1

You can make it easier with method overload rather than with generics:

public static int compare(Time value1, Time value2) {
   return DateComparator.compareTimes(value1, value2);
}

public static int compare(Number value1, Number value2) {
   return NumberUtility.compare(value1, value2);
}

This eliminates unnecessary instanceof checks and gives some compile time type guarantees.

AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76
0

This one you checked generic type as String, and doesnt compile because 1 is not String:

UtilityClazz.<String>compare("dd", 1);

but below you dont check generic type, and automatically compiler checks it as Object, and Object type is passed.

compare(SomeObject.getDate(), 1);

You must add Object case to your compare method

nikli
  • 2,281
  • 2
  • 24
  • 38
0

Instead of having a serie of if, you can make a map which associates a class to its comparator: Map<Class<?>,Comparator<?>>. The class is available through the getClass() method.

If you want to handle polymorphism, then you would have to call getSuperclass() on each object until you find a common ancestor.

T. Claverie
  • 11,380
  • 1
  • 17
  • 28