Java class comparator?
I want to compare two Java classes
class ClassComparator implements Comparator<Class> { @Override public int compare(Class arg0,Class arg1) { return ....; } }
I can only compare class names, but I want the parent analogy to be "smaller" than the class derived from them And I hope this less - than - normal relationship can be passed and applied to any two classes (to be honest, in my real problem, one class is always a superclass of another class, but I want some general case code, because theoretically this can be changed.)
Maybe this is done. Can anyone share code snippets?
What I think is: if no class derives from another class, find the two superclasses they derive from a common ancestor and compare their names (well, if any object is larger than any interface, it can even support interfaces.)
Solution
You can also compare classes that are not in a hierarchy with their depth and classes that are far away from the object class
class ClassComparator implements Comparator<Class> { @Override public int compare(Class arg0,Class arg1) { boolean arg0assignable = arg0.isAssignableFrom(arg1); boolean arg1assignable = arg1.isAssignableFrom(arg0); if (arg0assignable == arg1assignable && arg0assignable) { return 0; } else if (arg0assignable) { return -1; } else if (arg1assignable){ return 1; } else { return compareByDistanceToObject(arg0,arg1); } } private int compareByDistanceToObject(Class arg0,Class arg1) { int distanceToObject0 = getDistance(arg0); int distanceToObject1 = getDistance(arg1); if (distanceToObject0 == distanceToObject1) { return 0; } else if (distanceToObject0 < distanceToObject1) { return -1; } else { return 1; } } private int getDistance(Class clazz) { if (clazz == Object.class) { return 0; } return 1 + getDistance(clazz.getSuperclass()); }