1 10 11 package org.picocontainer.gems.adapters; 12 13 import com.thoughtworks.proxy.ProxyFactory; 14 import com.thoughtworks.proxy.factory.StandardProxyFactory; 15 import com.thoughtworks.proxy.toys.delegate.Delegating; 16 17 import org.picocontainer.ComponentAdapter; 18 import org.picocontainer.PicoContainer; 19 import org.picocontainer.PicoInitializationException; 20 import org.picocontainer.PicoIntrospectionException; 21 import org.picocontainer.defaults.DecoratingComponentAdapter; 22 23 import java.lang.reflect.Method ; 24 25 26 57 public class AssimilatingComponentAdapter extends DecoratingComponentAdapter { 58 59 private Class type; 60 private ProxyFactory proxyFactory; 61 private boolean isCompatible; 62 63 72 public AssimilatingComponentAdapter(final Class type, final ComponentAdapter delegate, final ProxyFactory proxyFactory) 73 throws PicoIntrospectionException { 74 super(delegate); 75 this.type = type; 76 this.proxyFactory = proxyFactory; 77 final Class delegationType = delegate.getComponentImplementation(); 78 this.isCompatible = type.isAssignableFrom(delegationType); 79 if (!isCompatible) { 80 if (!proxyFactory.canProxy(type)) { 81 throw new PicoIntrospectionException("Cannot create proxy for type " + type.getName()); 82 } 83 final Method [] methods = type.getMethods(); 84 for (int i = 0; i < methods.length; i++) { 85 final Method method = methods[i]; 86 try { 87 delegationType.getMethod(method.getName(), method.getParameterTypes()); 88 } catch (final NoSuchMethodException e) { 89 throw new PicoIntrospectionException("Cannot create proxy for type " 90 + type.getName() 91 + ", because of incompatible method " 92 + method.toString()); 93 } 94 } 95 } 96 } 97 98 106 public AssimilatingComponentAdapter(final Class type, final ComponentAdapter delegate) { 107 this(type, delegate, new StandardProxyFactory()); 108 } 109 110 116 public Object getComponentInstance(final PicoContainer container) 117 throws PicoInitializationException, PicoIntrospectionException { 118 return isCompatible ? super.getComponentInstance(container) : Delegating.object( 119 type, super.getComponentInstance(container), proxyFactory); 120 } 121 122 128 public Class getComponentImplementation() { 129 return isCompatible ? super.getComponentImplementation() : type; 130 } 131 132 138 public Object getComponentKey() { 139 final Object key = super.getComponentKey(); 140 if (key instanceof Class && (!isCompatible || !type.isAssignableFrom((Class )key))) { 141 return type; 142 } 143 return key; 144 } 145 } 146 | Popular Tags |