1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.batch.support;
18
19 import java.lang.annotation.Annotation;
20 import java.lang.annotation.ElementType;
21 import java.lang.annotation.Target;
22 import java.lang.reflect.Method;
23 import java.util.concurrent.atomic.AtomicReference;
24
25 import org.springframework.aop.support.AopUtils;
26 import org.springframework.core.annotation.AnnotationUtils;
27 import org.springframework.util.Assert;
28 import org.springframework.util.ObjectUtils;
29 import org.springframework.util.ReflectionUtils;
30
31
32
33
34
35
36
37 public class AnnotationMethodResolver implements MethodResolver {
38
39 private Class<? extends Annotation> annotationType;
40
41
42
43
44
45 public AnnotationMethodResolver(Class<? extends Annotation> annotationType) {
46 Assert.notNull(annotationType, "annotationType must not be null");
47 Assert.isTrue(ObjectUtils.containsElement(
48 annotationType.getAnnotation(Target.class).value(), ElementType.METHOD),
49 "Annotation [" + annotationType + "] is not a Method-level annotation.");
50 this.annotationType = annotationType;
51 }
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 @Override
68 public Method findMethod(Object candidate) {
69 Assert.notNull(candidate, "candidate object must not be null");
70 Class<?> targetClass = AopUtils.getTargetClass(candidate);
71 if (targetClass == null) {
72 targetClass = candidate.getClass();
73 }
74 return this.findMethod(targetClass);
75 }
76
77
78
79
80
81
82
83
84
85
86
87
88
89 @Override
90 public Method findMethod(final Class<?> clazz) {
91 Assert.notNull(clazz, "class must not be null");
92 final AtomicReference<Method> annotatedMethod = new AtomicReference<Method>();
93 ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
94 @Override
95 public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
96 Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
97 if (annotation != null) {
98 Assert.isNull(annotatedMethod.get(), "found more than one method on target class ["
99 + clazz + "] with the annotation type [" + annotationType + "]");
100 annotatedMethod.set(method);
101 }
102 }
103 });
104 return annotatedMethod.get();
105 }
106
107 }