View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.event.support;
20  
21  import java.util.Comparator;
22  
23  /**
24   * Compares two event classes based on their position in a class hierarchy.  Classes higher up in a hierarchy are
25   * 'greater than' (ordered later) than classes lower in a hierarchy (ordered earlier).  Classes in unrelated
26   * hierarchies have the same order priority.
27   * <p/>
28   * Event bus implementations use this comparator to determine which event listener method to invoke when polymorphic
29   * listener methods are defined:
30   * <p/>
31   * If two event classes exist A and B, where A is the parent class of B (and B is a subclass of A) and an event
32   * subscriber listens to both events:
33   * <pre>
34   * &#64;Subscribe
35   * public void onEvent(A a) { ... }
36   *
37   * &#64;Subscribe
38   * public void onEvent(B b) { ... }
39   * </pre>
40   *
41   * The {@code onEvent(B b)} method will be invoked on the subscriber and the
42   * {@code onEvent(A a)} method will <em>not</em> be invoked.  This is to prevent multiple dispatching of a single event
43   * to the same consumer.
44   * <p/>
45   * The EventClassComparator is used to order listener method priority based on their event argument class - methods
46   * handling event subclasses have higher precedence than superclasses.
47   *
48   * @since 1.3
49   */
50  public class EventClassComparator implements Comparator<Class> {
51  
52      @SuppressWarnings("unchecked")
53      public int compare(Class a, Class b) {
54          if (a == null) {
55              if (b == null) {
56                  return 0;
57              } else {
58                  return -1;
59              }
60          } else if (b == null) {
61              return 1;
62          } else if (a == b || a.equals(b)) {
63              return 0;
64          } else {
65              if (a.isAssignableFrom(b)) {
66                  return 1;
67              } else if (b.isAssignableFrom(a)) {
68                  return -1;
69              } else {
70                  return 0;
71              }
72          }
73      }
74  }