1   /*
2    * Copyright 2004-2009 the Seasar Foundation and the Others.
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
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  }