/* * 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 */ public class Binding { private Class clazz; private Class annotation; private Object value; private Map> 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 aClass, Class aAnnotation, Object aValue) { clazz = aClass; annotation = aAnnotation; value = aValue; accessorCache = new ConcurrentHashMap>(); } public void inject(Object aObject) { List accessors = getAccessors(aObject); for (Accessor accessor : accessors) { if (clazz.isAssignableFrom(accessor.getType())) { accessor.set(aObject, value); } } } private List getAccessors(Object aObject) { Class type = aObject.getClass(); List accessors = accessorCache.get(type); if (accessors == null) { accessors = AnnotationUtils.analyse(aObject.getClass(), annotation); accessorCache.put(type, accessors); } return accessors; } }