2 * Copyright 2005-2010 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.test.inject;
18 import java.lang.annotation.Annotation;
19 import java.util.List;
21 import java.util.concurrent.ConcurrentHashMap;
23 import org.wamblee.reflection.Accessor;
24 import org.wamblee.reflection.AnnotationUtils;
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.
32 * @author Erik Brakkee
36 public class Binding<T> {
37 private Class<T> clazz;
38 private Class<? extends Annotation> annotation;
40 private Map<Class, List<Accessor>> accessorCache;
43 * Constructs the binding.
46 * Required type of the field injected into.
48 * Annotation that must be present on the field.
52 public Binding(Class<T> aClass, Class<? extends Annotation> aAnnotation,
55 annotation = aAnnotation;
57 accessorCache = new ConcurrentHashMap<Class, List<Accessor>>();
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);
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);