001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.core; 018 019import java.lang.reflect.Method; 020 021import org.springframework.lang.Nullable; 022import org.springframework.util.ObjectUtils; 023 024/** 025 * A common key class for a method against a specific target class, 026 * including {@link #toString()} representation and {@link Comparable} 027 * support (as suggested for custom {@code HashMap} keys as of Java 8). 028 * 029 * @author Juergen Hoeller 030 * @since 4.3 031 */ 032public final class MethodClassKey implements Comparable<MethodClassKey> { 033 034 private final Method method; 035 036 @Nullable 037 private final Class<?> targetClass; 038 039 040 /** 041 * Create a key object for the given method and target class. 042 * @param method the method to wrap (must not be {@code null}) 043 * @param targetClass the target class that the method will be invoked 044 * on (may be {@code null} if identical to the declaring class) 045 */ 046 public MethodClassKey(Method method, @Nullable Class<?> targetClass) { 047 this.method = method; 048 this.targetClass = targetClass; 049 } 050 051 052 @Override 053 public boolean equals(@Nullable Object other) { 054 if (this == other) { 055 return true; 056 } 057 if (!(other instanceof MethodClassKey)) { 058 return false; 059 } 060 MethodClassKey otherKey = (MethodClassKey) other; 061 return (this.method.equals(otherKey.method) && 062 ObjectUtils.nullSafeEquals(this.targetClass, otherKey.targetClass)); 063 } 064 065 @Override 066 public int hashCode() { 067 return this.method.hashCode() + (this.targetClass != null ? this.targetClass.hashCode() * 29 : 0); 068 } 069 070 @Override 071 public String toString() { 072 return this.method + (this.targetClass != null ? " on " + this.targetClass : ""); 073 } 074 075 @Override 076 public int compareTo(MethodClassKey other) { 077 int result = this.method.getName().compareTo(other.method.getName()); 078 if (result == 0) { 079 result = this.method.toString().compareTo(other.method.toString()); 080 if (result == 0 && this.targetClass != null && other.targetClass != null) { 081 result = this.targetClass.getName().compareTo(other.targetClass.getName()); 082 } 083 } 084 return result; 085 } 086 087}