Elffuss BraidHub

kikocis/java-driver public

941704f40983 · 8.1 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;
19
20import java.beans.BeanInfo;
21import java.beans.IntrospectionException;
22import java.beans.Introspector;
23import java.beans.PropertyDescriptor;
24import java.lang.annotation.Annotation;
25import java.lang.reflect.*;
26import java.util.HashMap;
27import java.util.Map;
28
29/**
30 * Utility methods related to reflection.
31 */
32class ReflectionUtils {
33
34 static <T> T newInstance(Class<T> clazz) {
35 Constructor<T> publicConstructor;
36 try {
37 publicConstructor = clazz.getConstructor();
38 } catch (NoSuchMethodException e) {
39 try {
40 // try private constructor
41 Constructor<T> privateConstructor = clazz.getDeclaredConstructor();
42 privateConstructor.setAccessible(true);
43 return privateConstructor.newInstance();
44 } catch (Exception e1) {
45 throw new IllegalArgumentException("Can't create an instance of " + clazz, e);
46 }
47 }
48 try {
49 return publicConstructor.newInstance();
50 } catch (Exception e) {
51 throw new IllegalArgumentException("Can't create an instance of " + clazz, e);
52 }
53 }
54
55 // for each key representing a property name,
56 // value[0] contains a Field object, value[1] contains a PropertyDescriptor object;
57 // they cannot be both null at the same time
58 static <T> Map<String, Object[]> scanFieldsAndProperties(Class<T> baseClass) {
59 Map<String, Object[]> fieldsAndProperties = new HashMap<String, Object[]>();
60 Map<String, Field> fields = scanFields(baseClass);
61 for (Map.Entry<String, Field> entry : fields.entrySet()) {
62 fieldsAndProperties.put(entry.getKey(), new Object[]{entry.getValue(), null});
63 }
64 Map<String, PropertyDescriptor> properties = scanProperties(baseClass);
65 for (Map.Entry<String, PropertyDescriptor> entry : properties.entrySet()) {
66 Object[] value = fieldsAndProperties.get(entry.getKey());
67 if (value == null)
68 fieldsAndProperties.put(entry.getKey(), new Object[]{null, entry.getValue()});
69 else value[1] = entry.getValue();
70 }
71 return fieldsAndProperties;
72 }
73
74 private static <T> Map<String, Field> scanFields(Class<T> baseClass) {
75 HashMap<String, Field> fields = new HashMap<String, Field>();
76 for (Class<?> clazz = baseClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
77 for (Field field : clazz.getDeclaredFields()) {
78 if (field.getName().equals("class") || field.isSynthetic() || Modifier.isStatic(field.getModifiers()))
79 continue;
80 // never override a more specific field masking another one declared in a superclass
81 if (!fields.containsKey(field.getName()))
82 fields.put(field.getName(), field);
83 }
84 }
85 return fields;
86 }
87
88 private static <T> Map<String, PropertyDescriptor> scanProperties(Class<T> baseClass) {
89 BeanInfo beanInfo;
90 try {
91 beanInfo = Introspector.getBeanInfo(baseClass);
92 } catch (IntrospectionException e) {
93 throw Throwables.propagate(e);
94 }
95 Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>();
96 for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
97 if (property.getName().equals("class"))
98 continue;
99 properties.put(property.getName(), property);
100 }
101 return properties;
102 }
103
104 static Map<Class<? extends Annotation>, Annotation> scanPropertyAnnotations(Field field, PropertyDescriptor property) {
105 Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<Class<? extends Annotation>, Annotation>();
106 // annotations on getters should have precedence over annotations on fields
107 if (field != null)
108 scanFieldAnnotations(field, annotations);
109 Method getter = findGetter(property);
110 if (getter != null)
111 scanMethodAnnotations(getter, annotations);
112 return annotations;
113 }
114
115 private static Map<Class<? extends Annotation>, Annotation> scanFieldAnnotations(Field field, Map<Class<? extends Annotation>, Annotation> annotations) {
116 for (Annotation annotation : field.getAnnotations()) {
117 annotations.put(annotation.annotationType(), annotation);
118 }
119 return annotations;
120 }
121
122 private static Map<Class<? extends Annotation>, Annotation> scanMethodAnnotations(Method method, Map<Class<? extends Annotation>, Annotation> annotations) {
123 // 1. direct method annotations
124 for (Annotation annotation : method.getAnnotations()) {
125 annotations.put(annotation.annotationType(), annotation);
126 }
127 // 2. Class hierarchy: check for annotations in overridden methods in superclasses
128 Class<?> getterClass = method.getDeclaringClass();
129 for (Class<?> clazz = getterClass.getSuperclass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
130 maybeAddOverriddenMethodAnnotations(annotations, method, clazz);
131 }
132 // 3. Interfaces: check for annotations in implemented interfaces
133 for (Class<?> clazz = getterClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
134 for (Class<?> itf : clazz.getInterfaces()) {
135 maybeAddOverriddenMethodAnnotations(annotations, method, itf);
136 }
137 }
138 return annotations;
139 }
140
141 private static void maybeAddOverriddenMethodAnnotations(Map<Class<? extends Annotation>, Annotation> annotations, Method getter, Class<?> clazz) {
142 try {
143 Method overriddenGetter = clazz.getDeclaredMethod(getter.getName(), (Class[]) getter.getParameterTypes());
144 for (Annotation annotation : overriddenGetter.getAnnotations()) {
145 // do not override a more specific version of the annotation type being scanned
146 if (!annotations.containsKey(annotation.annotationType()))
147 annotations.put(annotation.annotationType(), annotation);
148 }
149 } catch (NoSuchMethodException e) {
150 //ok
151 }
152 }
153
154 static Method findGetter(PropertyDescriptor property) {
155 if (property == null)
156 return null;
157 Method getter = property.getReadMethod();
158 if (getter == null)
159 return null;
160 return getter;
161 }
162
163 static Method findSetter(Class<?> baseClass, PropertyDescriptor property) {
164 if (property == null)
165 return null;
166 Method setter = property.getWriteMethod();
167 if (setter != null)
168 return setter;
169 String propertyName = property.getName();
170 String setterName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
171 // JAVA-984: look for a "relaxed" setter, ie. a setter whose return type may be anything
172 try {
173 setter = baseClass.getMethod(setterName, property.getPropertyType());
174 if (!Modifier.isStatic(setter.getModifiers())) {
175 return setter;
176 }
177 } catch (NoSuchMethodException e) {
178 // ok
179 }
180 return null;
181 }
182
183 static void tryMakeAccessible(AccessibleObject object) {
184 if (!object.isAccessible()) {
185 try {
186 object.setAccessible(true);
187 } catch (SecurityException e) {
188 // ok
189 }
190 }
191 }
192
193}