View Javadoc

1   /***************************************************************************************
2    * Copyright (c) Jonas Bonér, Alexandre Vasseur. All rights reserved.                 *
3    * http://aspectwerkz.codehaus.org                                                    *
4    * ---------------------------------------------------------------------------------- *
5    * The software in this package is published under the terms of the LGPL license      *
6    * a copy of which has been included with this distribution in the license.txt file.  *
7    **************************************************************************************/
8   package org.codehaus.aspectwerkz.transform.delegation;
9   
10  import org.codehaus.aspectwerkz.exception.WrappedRuntimeException;
11  
12  import java.util.Comparator;
13  
14  import javassist.CtClass;
15  import javassist.CtMethod;
16  
17  /***
18   * Compares Javassist Methods. <p/>Based on code by Bob Lee (crazybob@crazybob.org)
19   * 
20   * @author <a href="mailto:jboner@codehaus.org">Jonas Bonér </a>
21   * @author <a href="mailto:alex@gnilux.com">Alexandre Vasseur </a>
22   */
23  public final class JavassistMethodComparator implements Comparator {
24      /***
25       * The sole instance.
26       */
27      private static final Comparator s_soleInstance = new JavassistMethodComparator();
28  
29      /***
30       * Returns the comparator instance.
31       * 
32       * @return the instance
33       */
34      public static Comparator getInstance() {
35          return s_soleInstance;
36      }
37  
38      /***
39       * Compares two objects
40       * 
41       * @param o1
42       * @param o2
43       * @return int
44       */
45      public int compare(final Object o1, final Object o2) {
46          return compare((CtMethod) o1, (CtMethod) o2);
47      }
48  
49      /***
50       * Compares two methods
51       * 
52       * @param m1
53       * @param m2
54       * @return int
55       */
56      private int compare(final CtMethod m1, final CtMethod m2) {
57          try {
58              if (!m1.getName().equals(m2.getName())) {
59                  return m1.getName().compareTo(m2.getName());
60              }
61              final CtClass[] args1 = m1.getParameterTypes();
62              final CtClass[] args2 = m2.getParameterTypes();
63              if (args1.length < args2.length) {
64                  return -1;
65              }
66              if (args1.length > args2.length) {
67                  return 1;
68              }
69              for (int i = 0; i < args1.length; i++) {
70                  int result = args1[i].getName().compareTo(args2[i].getName());
71                  if (result != 0) {
72                      return result;
73                  }
74              }
75          } catch (Throwable e) {
76              throw new WrappedRuntimeException(e);
77          }
78          throw new Error("classes can only be transformed once");
79      }
80  }