001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.shiro.event.support;
020
021import java.util.Comparator;
022
023/**
024 * Compares two event classes based on their position in a class hierarchy.  Classes higher up in a hierarchy are
025 * 'greater than' (ordered later) than classes lower in a hierarchy (ordered earlier).  Classes in unrelated
026 * hierarchies have the same order priority.
027 * <p/>
028 * Event bus implementations use this comparator to determine which event listener method to invoke when polymorphic
029 * listener methods are defined:
030 * <p/>
031 * 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
032 * subscriber listens to both events:
033 * <pre>
034 * &#64;Subscribe
035 * public void onEvent(A a) { ... }
036 *
037 * &#64;Subscribe
038 * public void onEvent(B b) { ... }
039 * </pre>
040 *
041 * The {@code onEvent(B b)} method will be invoked on the subscriber and the
042 * {@code onEvent(A a)} method will <em>not</em> be invoked.  This is to prevent multiple dispatching of a single event
043 * to the same consumer.
044 * <p/>
045 * The EventClassComparator is used to order listener method priority based on their event argument class - methods
046 * handling event subclasses have higher precedence than superclasses.
047 *
048 * @since 1.3
049 */
050public class EventClassComparator implements Comparator<Class> {
051
052    @SuppressWarnings("unchecked")
053    public int compare(Class a, Class b) {
054        if (a == null) {
055            if (b == null) {
056                return 0;
057            } else {
058                return -1;
059            }
060        } else if (b == null) {
061            return 1;
062        } else if (a == b || a.equals(b)) {
063            return 0;
064        } else {
065            if (a.isAssignableFrom(b)) {
066                return 1;
067            } else if (b.isAssignableFrom(a)) {
068                return -1;
069            } else {
070                return 0;
071            }
072        }
073    }
074}