Created
October 10, 2013 09:55
-
-
Save neolitec/6915884 to your computer and use it in GitHub Desktop.
smartCompare function for Java beans
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SuppressWarnings({ "unchecked", "rawtypes" }) | |
private int smartCompare(final Object o1, final Object o2, String field, final Class comparable) { | |
try { | |
if (o1 == o2) { | |
return 0; | |
} else if (o1 != null && o2 == null) { | |
return -1; | |
} else if (o1 == null && o2 != null) { | |
return 1; | |
} | |
Field f1 = o1.getClass().getField(field); | |
f1.setAccessible(true); | |
Field f2 = o2.getClass().getField(field); | |
f2.setAccessible(true); | |
if (f1.get(o1) == f2.get(o2)) { | |
return 0; | |
} else if (f1.get(o1) != null && f2.get(o2) == null) { | |
return -1; | |
} else if (f1.get(o1) == null && f2.get(o2) != null) { | |
return 1; | |
} | |
// If the two provided objects are Comparable then we can directly compare them. | |
if(null == comparable && f1.get(o1) instanceof Comparable && f2.get(o2) instanceof Comparable) { | |
return ((Comparable) f1.get(o1)).compareTo(f2.get(o2)); | |
} else { | |
// If a Comparable is provided, we use it. | |
if(Comparable.class.isAssignableFrom(comparable)) { | |
Constructor<?> ctor1 = comparable.getConstructor(o1.getClass()); | |
Comparable c1 = (Comparable) ctor1.newInstance(f1.get(o1)); | |
Constructor<?> ctor2 = comparable.getConstructor(o2.getClass()); | |
Comparable c2 = (Comparable) ctor2.newInstance(f2.get(o2)); | |
return c1.compareTo(c2); | |
} else { | |
throw new Exception(comparable.getName() + " does not implement Comparable"); | |
} | |
} | |
} catch (Exception e) { | |
NotificationHelper.error("Technical error : " + e.getMessage()); | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment