/
SynthesizedMergedAnnotationInvocationHandler.java
326 lines (295 loc) · 9.84 KB
/
SynthesizedMergedAnnotationInvocationHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* {@link InvocationHandler} for an {@link Annotation} that Spring has
* <em>synthesized</em> (i.e. wrapped in a dynamic proxy) with additional
* functionality such as attribute alias handling.
*
* @author Sam Brannen
* @author Phillip Webb
* @since 5.2
* @param <A> the annotation type
* @see Annotation
* @see AnnotationUtils#synthesizeAnnotation(Annotation, AnnotatedElement)
*/
final class SynthesizedMergedAnnotationInvocationHandler<A extends Annotation> implements InvocationHandler {
private final MergedAnnotation<?> annotation;
private final Class<A> type;
private final AttributeMethods attributes;
private final Map<String, Object> valueCache = new ConcurrentHashMap<>(8);
@Nullable
private volatile Integer hashCode;
@Nullable
private volatile String string;
private SynthesizedMergedAnnotationInvocationHandler(MergedAnnotation<A> annotation, Class<A> type) {
Assert.notNull(annotation, "MergedAnnotation must not be null");
Assert.notNull(type, "Type must not be null");
Assert.isTrue(type.isAnnotation(), "Type must be an annotation");
this.annotation = annotation;
this.type = type;
this.attributes = AttributeMethods.forAnnotationType(type);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
if (ReflectionUtils.isEqualsMethod(method)) {
return annotationEquals(args[0]);
}
if (ReflectionUtils.isHashCodeMethod(method)) {
return annotationHashCode();
}
if (ReflectionUtils.isToStringMethod(method)) {
return annotationToString();
}
if (isAnnotationTypeMethod(method)) {
return this.type;
}
if (this.attributes.indexOf(method.getName()) != -1) {
return getAttributeValue(method);
}
throw new AnnotationConfigurationException(String.format(
"Method [%s] is unsupported for synthesized annotation type [%s]", method, this.type));
}
private boolean isAnnotationTypeMethod(Method method) {
return (method.getName().equals("annotationType") && method.getParameterCount() == 0);
}
/**
* See {@link Annotation#equals(Object)} for a definition of the required algorithm.
* @param other the other object to compare against
*/
private boolean annotationEquals(Object other) {
if (this == other) {
return true;
}
if (!this.type.isInstance(other)) {
return false;
}
for (int i = 0; i < this.attributes.size(); i++) {
Method attribute = this.attributes.get(i);
Object thisValue = getAttributeValue(attribute);
Object otherValue = AnnotationUtils.invokeAnnotationMethod(attribute, other);
if (!ObjectUtils.nullSafeEquals(thisValue, otherValue)) {
return false;
}
}
return true;
}
/**
* See {@link Annotation#hashCode()} for a definition of the required algorithm.
*/
private int annotationHashCode() {
Integer hashCode = this.hashCode;
if (hashCode == null) {
hashCode = computeHashCode();
this.hashCode = hashCode;
}
return hashCode;
}
private Integer computeHashCode() {
int hashCode = 0;
for (int i = 0; i < this.attributes.size(); i++) {
Method attribute = this.attributes.get(i);
Object value = getAttributeValue(attribute);
hashCode += (127 * attribute.getName().hashCode()) ^ getValueHashCode(value);
}
return hashCode;
}
private int getValueHashCode(Object value) {
// Use Arrays.hashCode(...) since Spring's ObjectUtils doesn't comply
// with the requirements specified in Annotation#hashCode().
if (value instanceof boolean[]) {
return Arrays.hashCode((boolean[]) value);
}
if (value instanceof byte[]) {
return Arrays.hashCode((byte[]) value);
}
if (value instanceof char[]) {
return Arrays.hashCode((char[]) value);
}
if (value instanceof double[]) {
return Arrays.hashCode((double[]) value);
}
if (value instanceof float[]) {
return Arrays.hashCode((float[]) value);
}
if (value instanceof int[]) {
return Arrays.hashCode((int[]) value);
}
if (value instanceof long[]) {
return Arrays.hashCode((long[]) value);
}
if (value instanceof short[]) {
return Arrays.hashCode((short[]) value);
}
if (value instanceof Object[]) {
return Arrays.hashCode((Object[]) value);
}
return value.hashCode();
}
private String annotationToString() {
String string = this.string;
if (string == null) {
StringBuilder builder = new StringBuilder("@").append(getName(this.type)).append('(');
for (int i = 0; i < this.attributes.size(); i++) {
Method attribute = this.attributes.get(i);
if (i > 0) {
builder.append(", ");
}
builder.append(attribute.getName());
builder.append('=');
builder.append(toString(getAttributeValue(attribute)));
}
builder.append(')');
string = builder.toString();
this.string = string;
}
return string;
}
/**
* This method currently does not address the following issues which we may
* choose to address at a later point in time.
*
* <ul>
* <li>non-ASCII, non-visible, and non-printable characters within a character
* or String literal are not escaped.</li>
* <li>formatting for float and double values does not take into account whether
* a value is not a number (NaN) or infinite.</li>
* </ul>
* @param value the attribute value to format
* @return the formatted string representation
*/
private String toString(Object value) {
if (value instanceof String) {
return '"' + value.toString() + '"';
}
if (value instanceof Character) {
return '\'' + value.toString() + '\'';
}
if (value instanceof Byte) {
return String.format("(byte) 0x%02X", value);
}
if (value instanceof Long) {
return Long.toString(((Long) value)) + 'L';
}
if (value instanceof Float) {
return Float.toString(((Float) value)) + 'f';
}
if (value instanceof Double) {
return Double.toString(((Double) value)) + 'd';
}
if (value instanceof Enum) {
return ((Enum<?>) value).name();
}
if (value instanceof Class) {
return getName((Class<?>) value) + ".class";
}
if (value.getClass().isArray()) {
StringBuilder builder = new StringBuilder("{");
for (int i = 0; i < Array.getLength(value); i++) {
if (i > 0) {
builder.append(", ");
}
builder.append(toString(Array.get(value, i)));
}
builder.append('}');
return builder.toString();
}
return String.valueOf(value);
}
private Object getAttributeValue(Method method) {
Object value = this.valueCache.computeIfAbsent(method.getName(), attributeName -> {
Class<?> type = ClassUtils.resolvePrimitiveIfNecessary(method.getReturnType());
return this.annotation.getValue(attributeName, type).orElseThrow(
() -> new NoSuchElementException("No value found for attribute named '" + attributeName +
"' in merged annotation " + this.annotation.getType().getName()));
});
// Clone non-empty arrays so that users cannot alter the contents of values in our cache.
if (value.getClass().isArray() && Array.getLength(value) > 0) {
value = cloneArray(value);
}
return value;
}
/**
* Clone the provided array, ensuring that the original component type is retained.
* @param array the array to clone
*/
private Object cloneArray(Object array) {
if (array instanceof boolean[]) {
return ((boolean[]) array).clone();
}
if (array instanceof byte[]) {
return ((byte[]) array).clone();
}
if (array instanceof char[]) {
return ((char[]) array).clone();
}
if (array instanceof double[]) {
return ((double[]) array).clone();
}
if (array instanceof float[]) {
return ((float[]) array).clone();
}
if (array instanceof int[]) {
return ((int[]) array).clone();
}
if (array instanceof long[]) {
return ((long[]) array).clone();
}
if (array instanceof short[]) {
return ((short[]) array).clone();
}
// else
return ((Object[]) array).clone();
}
@SuppressWarnings("unchecked")
static <A extends Annotation> A createProxy(MergedAnnotation<A> annotation, Class<A> type) {
ClassLoader classLoader = type.getClassLoader();
InvocationHandler handler = new SynthesizedMergedAnnotationInvocationHandler<>(annotation, type);
Class<?>[] interfaces = isVisible(classLoader, SynthesizedAnnotation.class) ?
new Class<?>[] {type, SynthesizedAnnotation.class} : new Class<?>[] {type};
return (A) Proxy.newProxyInstance(classLoader, interfaces, handler);
}
private static String getName(Class<?> clazz) {
String canonicalName = clazz.getCanonicalName();
return (canonicalName != null ? canonicalName : clazz.getName());
}
private static boolean isVisible(ClassLoader classLoader, Class<?> interfaceClass) {
if (classLoader == interfaceClass.getClassLoader()) {
return true;
}
try {
return Class.forName(interfaceClass.getName(), false, classLoader) == interfaceClass;
}
catch (ClassNotFoundException ex) {
return false;
}
}
}