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