Elffuss BraidHub

kikocis/java-driver public

3.1.x · 8.5 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import com.google.common.base.Throwables;
19import com.google.common.collect.ImmutableSet;
20
21import java.beans.BeanInfo;
22import java.beans.IntrospectionException;
23import java.beans.Introspector;
24import java.beans.PropertyDescriptor;
25import java.lang.annotation.Annotation;
26import java.lang.reflect.*;
27import java.util.HashMap;
28import java.util.Map;
29import java.util.Set;
30
31/**
32 * Utility methods related to reflection.
33 */
34class ReflectionUtils {
35
36 private static final Set<String> EXCLUDED_PROPERTIES = ImmutableSet.of(
37 "class",
38 // JAVA-1279: exclude Groovy's metaClass property
39 "metaClass"
40 );
41
42 static <T> T newInstance(Class<T> clazz) {
43 Constructor<T> publicConstructor;
44 try {
45 publicConstructor = clazz.getConstructor();
46 } catch (NoSuchMethodException e) {
47 try {
48 // try private constructor
49 Constructor<T> privateConstructor = clazz.getDeclaredConstructor();
50 privateConstructor.setAccessible(true);
51 return privateConstructor.newInstance();
52 } catch (Exception e1) {
53 throw new IllegalArgumentException("Can't create an instance of " + clazz, e);
54 }
55 }
56 try {
57 return publicConstructor.newInstance();
58 } catch (Exception e) {
59 throw new IllegalArgumentException("Can't create an instance of " + clazz, e);
60 }
61 }
62
63 // for each key representing a property name,
64 // value[0] contains a Field object, value[1] contains a PropertyDescriptor object;
65 // they cannot be both null at the same time
66 static <T> Map<String, Object[]> scanFieldsAndProperties(Class<T> baseClass) {
67 Map<String, Object[]> fieldsAndProperties = new HashMap<String, Object[]>();
68 Map<String, Field> fields = scanFields(baseClass);
69 for (Map.Entry<String, Field> entry : fields.entrySet()) {
70 fieldsAndProperties.put(entry.getKey(), new Object[]{entry.getValue(), null});
71 }
72 Map<String, PropertyDescriptor> properties = scanProperties(baseClass);
73 for (Map.Entry<String, PropertyDescriptor> entry : properties.entrySet()) {
74 Object[] value = fieldsAndProperties.get(entry.getKey());
75 if (value == null)
76 fieldsAndProperties.put(entry.getKey(), new Object[]{null, entry.getValue()});
77 else value[1] = entry.getValue();
78 }
79 return fieldsAndProperties;
80 }
81
82 private static <T> Map<String, Field> scanFields(Class<T> baseClass) {
83 HashMap<String, Field> fields = new HashMap<String, Field>();
84 for (Class<?> clazz = baseClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
85 for (Field field : clazz.getDeclaredFields()) {
86 if (field.isSynthetic() || Modifier.isStatic(field.getModifiers()) || isPropertyExcluded(field.getName()))
87 continue;
88 // never override a more specific field masking another one declared in a superclass
89 if (!fields.containsKey(field.getName()))
90 fields.put(field.getName(), field);
91 }
92 }
93 return fields;
94 }
95
96 private static <T> Map<String, PropertyDescriptor> scanProperties(Class<T> baseClass) {
97 BeanInfo beanInfo;
98 try {
99 beanInfo = Introspector.getBeanInfo(baseClass);
100 } catch (IntrospectionException e) {
101 throw Throwables.propagate(e);
102 }
103 Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>();
104 for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
105 if (isPropertyExcluded(property.getName()))
106 continue;
107 properties.put(property.getName(), property);
108 }
109 return properties;
110 }
111
112 private static boolean isPropertyExcluded(String name) {
113 return EXCLUDED_PROPERTIES.contains(name);
114 }
115
116 static Map<Class<? extends Annotation>, Annotation> scanPropertyAnnotations(Field field, PropertyDescriptor property) {
117 Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<Class<? extends Annotation>, Annotation>();
118 // annotations on getters should have precedence over annotations on fields
119 if (field != null)
120 scanFieldAnnotations(field, annotations);
121 Method getter = findGetter(property);
122 if (getter != null)
123 scanMethodAnnotations(getter, annotations);
124 return annotations;
125 }
126
127 private static Map<Class<? extends Annotation>, Annotation> scanFieldAnnotations(Field field, Map<Class<? extends Annotation>, Annotation> annotations) {
128 for (Annotation annotation : field.getAnnotations()) {
129 annotations.put(annotation.annotationType(), annotation);
130 }
131 return annotations;
132 }
133
134 private static Map<Class<? extends Annotation>, Annotation> scanMethodAnnotations(Method method, Map<Class<? extends Annotation>, Annotation> annotations) {
135 // 1. direct method annotations
136 for (Annotation annotation : method.getAnnotations()) {
137 annotations.put(annotation.annotationType(), annotation);
138 }
139 // 2. Class hierarchy: check for annotations in overridden methods in superclasses
140 Class<?> getterClass = method.getDeclaringClass();
141 for (Class<?> clazz = getterClass.getSuperclass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
142 maybeAddOverriddenMethodAnnotations(annotations, method, clazz);
143 }
144 // 3. Interfaces: check for annotations in implemented interfaces
145 for (Class<?> clazz = getterClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
146 for (Class<?> itf : clazz.getInterfaces()) {
147 maybeAddOverriddenMethodAnnotations(annotations, method, itf);
148 }
149 }
150 return annotations;
151 }
152
153 private static void maybeAddOverriddenMethodAnnotations(Map<Class<? extends Annotation>, Annotation> annotations, Method getter, Class<?> clazz) {
154 try {
155 Method overriddenGetter = clazz.getDeclaredMethod(getter.getName(), (Class[]) getter.getParameterTypes());
156 for (Annotation annotation : overriddenGetter.getAnnotations()) {
157 // do not override a more specific version of the annotation type being scanned
158 if (!annotations.containsKey(annotation.annotationType()))
159 annotations.put(annotation.annotationType(), annotation);
160 }
161 } catch (NoSuchMethodException e) {
162 //ok
163 }
164 }
165
166 static Method findGetter(PropertyDescriptor property) {
167 if (property == null)
168 return null;
169 Method getter = property.getReadMethod();
170 if (getter == null)
171 return null;
172 return getter;
173 }
174
175 static Method findSetter(Class<?> baseClass, PropertyDescriptor property) {
176 if (property == null)
177 return null;
178 Method setter = property.getWriteMethod();
179 if (setter != null)
180 return setter;
181 String propertyName = property.getName();
182 String setterName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
183 // JAVA-984: look for a "relaxed" setter, ie. a setter whose return type may be anything
184 try {
185 setter = baseClass.getMethod(setterName, property.getPropertyType());
186 if (!Modifier.isStatic(setter.getModifiers())) {
187 return setter;
188 }
189 } catch (NoSuchMethodException e) {
190 // ok
191 }
192 return null;
193 }
194
195 static void tryMakeAccessible(AccessibleObject object) {
196 if (!object.isAccessible()) {
197 try {
198 object.setAccessible(true);
199 } catch (SecurityException e) {
200 // ok
201 }
202 }
203 }
204
205}