1 package com.atlassian.plugins.rest.common.util;
2
3 import com.google.common.collect.Lists;
4 import org.apache.commons.lang.StringUtils;
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.AnnotatedElement;
10 import java.lang.reflect.Field;
11 import java.util.List;
12 import javax.annotation.Nonnull;
13 import javax.annotation.Nullable;
14
15 import static com.google.common.base.Preconditions.checkNotNull;
16 import static java.util.Arrays.asList;
17
18
19
20
21 public class ReflectionUtils {
22 private static final Logger log = LoggerFactory.getLogger(ReflectionUtils.class);
23
24 private ReflectionUtils() {
25 }
26
27
28
29
30
31
32
33
34
35 public static Object getFieldValue(Field field, Object object) {
36 final boolean accessible = field.isAccessible();
37 try {
38 if (!accessible) {
39 field.setAccessible(true);
40 }
41 return field.get(object);
42 } catch (IllegalAccessException e) {
43 throw new RuntimeException("Could not access '" + field + "' from '" + object + "'", e);
44 } finally {
45 if (!accessible) {
46 field.setAccessible(false);
47 }
48 }
49 }
50
51
52
53
54
55
56
57
58
59 public static void setFieldValue(Field field, Object object, Object value) {
60 final boolean accessible = field.isAccessible();
61 try {
62 if (!accessible) {
63 field.setAccessible(true);
64 }
65 field.set(object, value);
66 } catch (IllegalAccessException e) {
67 throw new RuntimeException("Could not access '" + field + "' from '" + object + "'", e);
68 } finally {
69 if (!accessible) {
70 field.setAccessible(false);
71 }
72 }
73 }
74
75
76
77
78
79
80
81
82
83
84 public static List<Field> getDeclaredFields(Class clazz) {
85 if (clazz == null) {
86 return Lists.newArrayList();
87 } else {
88 final List<Field> superFields = getDeclaredFields(clazz.getSuperclass());
89 superFields.addAll(0, asList(clazz.getDeclaredFields()));
90 return superFields;
91 }
92 }
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107 public static <T extends Annotation> T getAnnotation(@Nonnull final Class<T> annotationType, @Nullable final AnnotatedElement element) {
108 checkNotNull(annotationType, "An annotation is required");
109
110 if (element == null) {
111 return null;
112 }
113
114 for (Annotation a : element.getAnnotations()) {
115 if (StringUtils.equals(a.annotationType().getCanonicalName(), annotationType.getCanonicalName())) {
116 if (!a.annotationType().equals(annotationType)) {
117 log.warn("Detected usage of the {} annotation loaded from elsewhere. {} != {}",
118 annotationType.getCanonicalName(),
119 annotationType.getClassLoader(),
120 a.annotationType().getClassLoader());
121 return null;
122 }
123 return (T) a;
124 }
125 }
126 return null;
127 }
128 }