+/*
+ * Copyright 2005-2010 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wamblee.test.inject;
+
+import java.lang.annotation.Annotation;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.wamblee.reflection.Accessor;
+import org.wamblee.reflection.AnnotationUtils;
+
+/**
+ * This class represents an injection binding. It provides injection of a defined object (typically mock or stub)
+ * into other objects. The binding is defined by the required annotation that must be on the field, the field type,
+ * and the object to be injected.
+ *
+ * @author Erik Brakkee
+ *
+ * @param <T>
+ */
+public class Binding<T> {
+ private Class<T> clazz;
+ private Class<? extends Annotation> annotation;
+ private Object value;
+ private Map<Class, List<Accessor>> accessorCache;
+
+ /**
+ * Constructs the binding.
+ * @param aClass Required type of the field injected into.
+ * @param aAnnotation Annotation that must be present on the field.
+ * @param aValue Value of the annotation.
+ */
+ public Binding(Class<T> aClass, Class<? extends Annotation> aAnnotation,
+ Object aValue) {
+ clazz = aClass;
+ annotation = aAnnotation;
+ value = aValue;
+ accessorCache = new ConcurrentHashMap<Class, List<Accessor>>();
+ }
+
+ public void inject(Object aObject) {
+ List<Accessor> accessors = getAccessors(aObject);
+ for (Accessor accessor : accessors) {
+ if (clazz.isAssignableFrom(accessor.getType())) {
+ accessor.set(aObject, value);
+ }
+ }
+ }
+
+ private List<Accessor> getAccessors(Object aObject) {
+ Class type = aObject.getClass();
+ List<Accessor> accessors = accessorCache.get(type);
+ if (accessors == null) {
+ accessors = AnnotationUtils.analyse(aObject.getClass(), annotation);
+ accessorCache.put(type, accessors);
+ }
+ return accessors;
+ }
+}