1   /*
2    * Copyright 2004-2010 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  
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  }