Elffuss BraidHub

kikocis/java-driver public

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