(no commit message)
[utils] / test / enterprise / src / main / java / org / wamblee / test / inject / Binding.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
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 org.wamblee.test.inject;
17
18 import java.lang.annotation.Annotation;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.concurrent.ConcurrentHashMap;
22
23 import org.wamblee.reflection.Accessor;
24 import org.wamblee.reflection.AnnotationUtils;
25
26 /**
27  * This class represents an injection binding. It provides injection of a defined object (typically mock or stub)
28  * into other objects. The binding is defined by the required annotation that must be on the field, the field type, 
29  * and the object to be injected. 
30  * 
31  * @author Erik Brakkee
32  *
33  * @param <T>
34  */
35 public class Binding<T> {
36     private Class<T> clazz;
37     private Class<? extends Annotation> annotation;
38     private Object value;
39     private Map<Class, List<Accessor>> accessorCache;
40
41     /**
42      * Constructs the binding. 
43      * @param aClass Required type of the field injected into. 
44      * @param aAnnotation Annotation that must be present on the field.
45      * @param aValue Value of the annotation. 
46      */
47     public Binding(Class<T> aClass, Class<? extends Annotation> aAnnotation,
48         Object aValue) {
49         clazz = aClass;
50         annotation = aAnnotation;
51         value = aValue;
52         accessorCache = new ConcurrentHashMap<Class, List<Accessor>>();
53     }
54
55     public void inject(Object aObject) {
56         List<Accessor> accessors = getAccessors(aObject);
57         for (Accessor accessor : accessors) {
58             if (clazz.isAssignableFrom(accessor.getType())) {
59                 accessor.set(aObject, value);
60             }
61         }
62     }
63
64     private List<Accessor> getAccessors(Object aObject) {
65         Class type = aObject.getClass();
66         List<Accessor> accessors = accessorCache.get(type);
67         if (accessors == null) {
68             accessors = AnnotationUtils.analyse(aObject.getClass(), annotation);
69             accessorCache.put(type, accessors);
70         }
71         return accessors;
72     }
73 }