1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.seasar.cubby;
18
19 import java.lang.reflect.Field;
20
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 public class TestUtils {
25
26 private static final Logger logger = LoggerFactory
27 .getLogger(TestUtils.class);
28
29 @SuppressWarnings("unchecked")
30 public static <T> T getPrivateField(Object obj, String fieldName)
31 throws NoSuchFieldException {
32
33 Class<?> class1 = obj.getClass();
34 final Field field = findField(class1, fieldName);
35 field.setAccessible(true);
36
37 try {
38 return (T) field.get(obj);
39 } catch (IllegalAccessException e) {
40 throw new RuntimeException(e);
41 }
42 }
43
44 private static Field findField(Class<?> clazz, String fieldName)
45 throws NoSuchFieldException {
46 for (; clazz != null; clazz = clazz.getSuperclass()) {
47 for (Field afield : clazz.getDeclaredFields()) {
48 if (afield.getName().equals(fieldName)) {
49 return afield;
50 }
51 }
52 }
53
54 throw new NoSuchFieldException(fieldName);
55 }
56
57 public static void bind(Object client, Object injectee) {
58 Class<?> clientType = client.getClass();
59 bind(client, clientType, injectee);
60 }
61
62 private static void bind(Object client, Class<?> clientType, Object injectee) {
63 for (Field field : clientType.getDeclaredFields()) {
64 if (field.getType().isAssignableFrom(injectee.getClass())) {
65 field.setAccessible(true);
66 try {
67 field.set(client, injectee);
68 logger.debug("Bind [" + field + "] to " + injectee);
69 } catch (IllegalArgumentException e) {
70 throw new RuntimeException(e);
71 } catch (IllegalAccessException e) {
72 throw new RuntimeException(e);
73 }
74 }
75 }
76 Class<?> superType = clientType.getSuperclass();
77 if (!superType.equals(Object.class)) {
78 bind(client, superType, injectee);
79 }
80 }
81
82 }