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.context.expression; 018 019import java.lang.reflect.AnnotatedElement; 020 021import org.springframework.lang.Nullable; 022import org.springframework.util.Assert; 023import org.springframework.util.ObjectUtils; 024 025/** 026 * Represent an {@link AnnotatedElement} on a particular {@link Class} 027 * and is suitable as a key. 028 * 029 * @author Costin Leau 030 * @author Stephane Nicoll 031 * @since 4.2 032 * @see CachedExpressionEvaluator 033 */ 034public final class AnnotatedElementKey implements Comparable<AnnotatedElementKey> { 035 036 private final AnnotatedElement element; 037 038 @Nullable 039 private final Class<?> targetClass; 040 041 042 /** 043 * Create a new instance with the specified {@link AnnotatedElement} and 044 * optional target {@link Class}. 045 */ 046 public AnnotatedElementKey(AnnotatedElement element, @Nullable Class<?> targetClass) { 047 Assert.notNull(element, "AnnotatedElement must not be null"); 048 this.element = element; 049 this.targetClass = targetClass; 050 } 051 052 053 @Override 054 public boolean equals(@Nullable Object other) { 055 if (this == other) { 056 return true; 057 } 058 if (!(other instanceof AnnotatedElementKey)) { 059 return false; 060 } 061 AnnotatedElementKey otherKey = (AnnotatedElementKey) other; 062 return (this.element.equals(otherKey.element) && 063 ObjectUtils.nullSafeEquals(this.targetClass, otherKey.targetClass)); 064 } 065 066 @Override 067 public int hashCode() { 068 return this.element.hashCode() + (this.targetClass != null ? this.targetClass.hashCode() * 29 : 0); 069 } 070 071 @Override 072 public String toString() { 073 return this.element + (this.targetClass != null ? " on " + this.targetClass : ""); 074 } 075 076 @Override 077 public int compareTo(AnnotatedElementKey other) { 078 int result = this.element.toString().compareTo(other.element.toString()); 079 if (result == 0 && this.targetClass != null) { 080 if (other.targetClass == null) { 081 return 1; 082 } 083 result = this.targetClass.getName().compareTo(other.targetClass.getName()); 084 } 085 return result; 086 } 087 088}