(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
28  * defined object (typically mock or stub) into other objects. The binding is
29  * defined by the required annotation that must be on the field, the field type,
30  * and the object to be injected.
31  * 
32  * @author Erik Brakkee
33  * 
34  * @param <T>
35  */
36 public class Binding<T> {
37     private Class<T> clazz;
38     private Class<? extends Annotation> annotation;
39     private Object value;
40     private Map<Class, List<Accessor>> accessorCache;
41
42     /**
43      * Constructs the binding.
44      * 
45      * @param aClass
46      *            Required type of the field injected into.
47      * @param aAnnotation
48      *            Annotation that must be present on the field.
49      * @param aValue
50      *            Value to inject.
51      */
52     public Binding(Class<T> aClass, Class<? extends Annotation> aAnnotation,
53         Object aValue) {
54         clazz = aClass;
55         annotation = aAnnotation;
56         value = aValue;
57         accessorCache = new ConcurrentHashMap<Class, List<Accessor>>();
58     }
59
60     public void inject(Object aObject) {
61         List<Accessor> accessors = getAccessors(aObject);
62         for (Accessor accessor : accessors) {
63             if (clazz.isAssignableFrom(accessor.getType())) {
64                 accessor.set(aObject, value);
65             }
66         }
67     }
68
69     private List<Accessor> getAccessors(Object aObject) {
70         Class type = aObject.getClass();
71         List<Accessor> accessors = accessorCache.get(type);
72         if (accessors == null) {
73             accessors = AnnotationUtils.analyse(aObject.getClass(), annotation);
74             accessorCache.put(type, accessors);
75         }
76         return accessors;
77     }
78 }