1 /*
2 * Copyright 2011 FatWire Corporation. All Rights Reserved.
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 */
16 package com.fatwire.gst.foundation.controller.annotation;
17
18 import java.lang.reflect.Field;
19
20 /**
21 * Helper class to work with Annotations.
22 *
23 * @author Dolf Dijkstra
24 * @since May 27, 2011
25 */
26 public final class AnnotationUtils {
27 private AnnotationUtils() {
28 }
29
30 /**
31 *
32 *
33 * @param <T> the class of the object that is returned .
34 * @param object the object containing the object to find.
35 * @param type the Class of the type that is searched for.
36 * @return the object that is present on the field with the InjectForRequest
37 * annotation.
38 */
39 @SuppressWarnings("unchecked")
40 public static <T> T findService(final Object object, final Class<T> type) {
41 final Field field = findField(object, type);
42 try {
43 return field == null ? null : (T) field.get(object);
44 } catch (final IllegalAccessException e) {
45 throw new RuntimeException(e);
46 }
47 }
48
49 /**
50 * Searches the object for a field annotated with the InjectForRequest
51 * annotation of the provided type.
52 * <p/>
53 *
54 * For instance <tt>@InjectForRequest Service service; </tt> is defined on
55 * the class as a field, then <tt>findField(object,Service.class);</tt> will
56 * return the Field <tt>service</tt>.
57 *
58 * @param <T> the type of the field to look for.
59 * @param a the object to search on for the typed field.
60 * @param type
61 * @return the class field with the InjectForRequest annotation of the Class
62 * type.
63 */
64 public static <T> Field findField(final Object a, final Class<T> type) {
65 Class<?> klazz = a.getClass();
66 while (klazz != null && klazz != Object.class) {
67 for (final Field field : klazz.getDeclaredFields()) {
68 if (field.getAnnotation(InjectForRequest.class) != null && type.isAssignableFrom(field.getType())) {
69 return field;
70 }
71 }
72 klazz = klazz.getSuperclass();
73 }
74 return null;
75 }
76
77 }