AttributeComparator implements Comparator<T> { @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public int compare(T o1, T o2) { Object v1 = ClassUtils.getFieldValue(o1, attribute); Object v2 = ClassUtils.getFieldValue(o2, attribute); if (v1 == null && v2 == null) { return 0; } else if (v1 == null) { return -1; } else if (v2 == null) { return 1; } else if (v1 instanceof String) { return ((String) v1).compareToIgnoreCase((String) v2); } else if (v1 instanceof Comparable) { return ((Comparable) v1).compareTo(v2); } return 0; } AttributeComparator(String attribute); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) int compare(T o1, T o2);  }
@Test public void test() { TestEntity t1 = new TestEntity("bert", 44L); TestEntity t2 = new TestEntity("chloe", 33L); TestEntity t3 = new TestEntity(null, 33L); assertEquals(0, new AttributeComparator<TestEntity>("name").compare(t1, t1)); assertEquals(-1, new AttributeComparator<TestEntity>("name").compare(t1, t2)); assertEquals(1, new AttributeComparator<TestEntity>("name").compare(t2, t1)); assertEquals(1, new AttributeComparator<TestEntity>("age").compare(t1, t2)); assertEquals(-1, new AttributeComparator<TestEntity>("age").compare(t2, t1)); assertEquals(1, new AttributeComparator<TestEntity>("name").compare(t1, t3)); assertEquals(-1, new AttributeComparator<TestEntity>("name").compare(t3, t1)); }