Created
February 26, 2014 22:21
-
-
Save CalebWhiting/9239924 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package edu.revtek.util; | |
| import java.lang.reflect.*; | |
| import java.util.*; | |
| /** | |
| * @author Caleb Whiting | |
| * | |
| * A convenient class for comparing values within objects | |
| */ | |
| public class PropertyComparator<T> implements Comparator<T> { | |
| private final Class<? extends Member> memberType; | |
| private final String name; | |
| public PropertyComparator(Class<? extends Member> memberType, String name) { | |
| this.memberType = memberType; | |
| this.name = name; | |
| } | |
| private Member getMember(Object o) { | |
| Class c = o.getClass(); | |
| if (memberType == Field.class) { | |
| for (Field f : c.getDeclaredFields()) { | |
| if (f.getName().equals(name)) { | |
| return f; | |
| } | |
| } | |
| } else if (memberType == Method.class) { | |
| for (Method method : c.getDeclaredMethods()) { | |
| if (method.getName().equals(name)) { | |
| return method; | |
| } | |
| } | |
| } else { | |
| throw new RuntimeException("Unsupported member type: " + c); | |
| } | |
| throw new RuntimeException(String.format("Couldn't find member for %s in class %s", name, c)); | |
| } | |
| private Object getValue(T t) throws ReflectiveOperationException { | |
| Member member = getMember(t); | |
| if (member instanceof Method) { | |
| return ((Method) member).invoke(t); | |
| } else { | |
| // no need to check, getMember would throw an exception | |
| // if the type wasn't field or method | |
| return ((Field) member).get(t); | |
| } | |
| } | |
| @Override | |
| public int compare(T t, T t1) { | |
| try { | |
| Object o = getValue(t); | |
| Object o1 = getValue(t1); | |
| try { | |
| //noinspection unchecked | |
| return ((Comparable) o).compareTo(o1); | |
| } catch (ClassCastException e) { | |
| throw new RuntimeException("Compared values must be instances of java.lang.Comparable", e); | |
| } | |
| } catch (ReflectiveOperationException e) { | |
| throw new RuntimeException(e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment