package net.sourceforge.javautil.dependency.mapper;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import net.sourceforge.javautil.common.reflection.cache.ClassCache;
import net.sourceforge.javautil.common.reflection.cache.ClassDescriptor;
import net.sourceforge.javautil.common.reflection.cache.ClassField;
import net.sourceforge.javautil.dependency.IDependancyRelationship;
import net.sourceforge.javautil.dependency.IDependencyManager;
import net.sourceforge.javautil.dependency.IManaged;
import net.sourceforge.javautil.dependency.annotation.Dependency;
/**
* An {@link IDependencyMapper} implementation based on the {@link Dependency} annotation.
*
* @author elponderador
* @author $Author$
* @version $Id$
*/
public class AnnotatedDependencyMapper<M extends IManaged<?>> implements IDependencyMapper<M> {
protected final IDependencyManager<M, IDependancyRelationship<M>> manager;
public AnnotatedDependencyMapper(IDependencyManager<M, IDependancyRelationship<M>> manager) {
this.manager = manager;
}
@Override public void map(M managed) {
ClassDescriptor<?> descriptor = ClassCache.getFor(managed.getClass());
Map<String, List<ClassField>> fields = descriptor.getFields();
for (String name : fields.keySet()) {
for (ClassField field : fields.get(name)) {
if (!IManaged.class.isAssignableFrom( field.getBaseType() )) continue;
for (Annotation annotation : field.getAnnotations()) {
Dependency dependency = annotation.annotationType().getAnnotation(Dependency.class);
if (dependency != null) {
field.ensureAccessibility();
manager.relate(managed, (M) field.getValue(managed), dependency.strategy());
}
}
}
}
}
}