Other answers are well described, why reflection is not recommended. I want to add an example using a more traditional solution.
Instead of specifying a field that is used to compare two objects, you should take an instance of Comparator as an argument. Thus, a client that uses this method can specify how to compare two objects.
protected <E> int compareFields(E o1, E o2, Comparator<E> comparator) { return comparator.compare(o1, o2); }
And an example call to this function would look like this:
MyClass a = ...; MyClass b = ...; Comparator<MyClass> intFieldComparator = new Comparator<MyClass> { public int compare(MyClass o1, MyClass o2) { int field1 = o1.getIntField(); int field2 = o2.getIntField(); return field2 - field1; } }; compareFields(a, b, intFieldComparator);
You can define different comparators if you want to compare objects using several fields.
source share