1 10 package org.picocontainer.alternatives; 11 12 import org.picocontainer.ComponentAdapter; 13 import org.picocontainer.PicoContainer; 14 import org.picocontainer.PicoInitializationException; 15 import org.picocontainer.PicoIntrospectionException; 16 import org.picocontainer.defaults.AssignabilityRegistrationException; 17 import org.picocontainer.defaults.DecoratingComponentAdapter; 18 import org.picocontainer.defaults.NotConcreteRegistrationException; 19 20 import java.lang.reflect.InvocationHandler ; 21 import java.lang.reflect.InvocationTargetException ; 22 import java.lang.reflect.Method ; 23 import java.lang.reflect.Proxy ; 24 25 39 public class ImplementationHidingComponentAdapter extends DecoratingComponentAdapter { 40 private final boolean strict; 41 42 public ImplementationHidingComponentAdapter(ComponentAdapter delegate, boolean strict) { 43 super(delegate); 44 this.strict = strict; 45 } 46 47 public Object getComponentInstance(final PicoContainer container) 48 throws PicoInitializationException, PicoIntrospectionException, AssignabilityRegistrationException, NotConcreteRegistrationException { 49 50 Object componentKey = getDelegate().getComponentKey(); 51 Class [] classes = null; 52 if (componentKey instanceof Class && ((Class ) getDelegate().getComponentKey()).isInterface()) { 53 classes = new Class []{(Class ) getDelegate().getComponentKey()}; 54 } else if (componentKey instanceof Class []) { 55 classes = (Class []) componentKey; 56 } else { 57 if(strict) { 58 throw new PicoIntrospectionException("In strict mode, " + getClass().getName() + " only allows components registered with interface keys (java.lang.Class or java.lang.Class[])"); 59 } 60 return getDelegate().getComponentInstance(container); 61 } 62 63 Class [] interfaces = verifyInterfacesOnly(classes); 64 return createProxy(interfaces, container); 65 } 66 67 private Object createProxy(Class [] interfaces, final PicoContainer container) { 68 return Proxy.newProxyInstance(getClass().getClassLoader(), 69 interfaces, new InvocationHandler () { 70 public Object invoke(final Object proxy, final Method method, 71 final Object [] args) 72 throws Throwable { 73 try { 74 Object componentInstance = getDelegate().getComponentInstance(container); 75 return method.invoke(componentInstance, args); 76 } catch (final InvocationTargetException ite) { 77 throw ite.getTargetException(); 78 } 79 } 80 }); 81 } 82 83 private Class [] verifyInterfacesOnly(Class [] classes) { 84 for (int i = 0; i < classes.length; i++) { 85 if(!classes[i].isInterface()) { 86 throw new PicoIntrospectionException("Class keys must be interfaces. " + classes[i] + " is not an interface."); 87 } 88 } 89 return classes; 90 } 91 92 104 129 } 130 | Popular Tags |