Sort by inheritance hierarchy of classes

  • Example shows

  Java provides interfaceof operator to compare whether there is inheritance relationship between two classes or interfaces. But if you use this method for more than one class in accordance with the inheritance sort would be very troublesome.

  • Key Technology

  TreeSet <E> is achieved based on a TreeMap NavigableSet. He uses natural ordering sorts the elements of the element, or sorted according to a Comparator provided at creating SET, depending on the configuration method. This example uses the class Class IsAssignableFrom () method to determine the relationship between the current class Class Class object with a given Class object represented Returns true if the same or a parent class, otherwise it returns false.

  public boolean isAssignableFrom(Class<?> cls)

  • designing process
public  class ClassComparator the implements Comparator { 
    @Override 
    // by implementing the comparison function Comparator interface 
    public  int Compare (Object O1, O2 Object) {
         IF (o1.equals (O2)) {
             return 0;                    // if two identical class object returns 0 
        }
         IF (o1.getClass () IsAssignableFrom (o2.getClass ()).) {
             return -1;                   // if o1 class represented o2 is the parent class of the class represented by -1 is returned 
        }
         IF (o2.getClass () .isAssignableFrom (o1.getClass ())) {
             return . 1;                    //If the class represented o1 o2 is a subclass of the class represented by a return 
        }
         the throw  new new an IllegalArgumentException ( "no relationship between the two classes" ); 
    } 

}

 

Guess you like

Origin www.cnblogs.com/cglib/p/11512504.html