001    package org.picocontainer.behaviors;
002    
003    import org.picocontainer.ComponentAdapter;
004    import org.picocontainer.PicoCompositionException;
005    import org.picocontainer.PicoContainer;
006    
007    import java.lang.reflect.Field;
008    import java.lang.reflect.Type;
009    
010    @SuppressWarnings("serial")
011    public class FieldDecorated extends AbstractBehavior {
012        private final Class<?> fieldClass;
013        private final Decorator decorator;
014    
015        public FieldDecorated(ComponentAdapter delegate, Class<?> fieldClass, Decorator decorator) {
016            super(delegate);
017            this.fieldClass = fieldClass;
018            this.decorator = decorator;
019        }
020    
021        public Object getComponentInstance(final PicoContainer container, Type into)
022                throws PicoCompositionException {
023            Object instance = super.getComponentInstance(container, into);
024            Field[] fields = instance.getClass().getDeclaredFields();
025            for (Field field : fields) {
026                if (field.getType() == fieldClass) {
027                    Object value = decorator.decorate(instance);
028                    field.setAccessible(true);
029                    try {
030                        field.set(instance, value);
031                    } catch (IllegalAccessException e) {
032                        throw new PicoCompositionException(e);
033                    }
034                }
035            }
036            return instance;
037        }
038    
039    
040        public String getDescriptor() {
041            return "FieldDecorated";
042        }
043    
044        public interface Decorator {
045    
046            Object decorate(Object instance);
047    
048    
049        }
050    
051    }