1 10 package org.picocontainer.defaults; 11 12 import java.io.Serializable ; 13 import java.lang.reflect.InvocationHandler ; 14 import java.lang.reflect.InvocationTargetException ; 15 import java.lang.reflect.Method ; 16 import java.lang.reflect.Proxy ; 17 18 import org.picocontainer.Disposable; 19 import org.picocontainer.PicoContainer; 20 import org.picocontainer.Startable; 21 22 23 29 public class ImmutablePicoContainerProxyFactory implements InvocationHandler , Serializable { 30 31 private static final Class [] interfaces = new Class []{PicoContainer.class}; 32 protected static Method startMethod = null; 33 protected static Method stopMethod = null; 34 protected static Method disposeMethod = null; 35 protected static Method equalsMethod = null; 36 37 static { 38 try { 39 startMethod = Startable.class.getMethod("start", new Class [0]); 40 stopMethod = Startable.class.getMethod("stop", new Class [0]); 41 disposeMethod = Disposable.class.getMethod("dispose", new Class [0]); 42 equalsMethod = Object .class.getMethod("equals", new Class []{Object .class}); 43 } catch (final NoSuchMethodException e) { 44 throw new InternalError (e.getMessage()); 45 } 46 } 47 48 private final PicoContainer pico; 49 50 57 protected ImmutablePicoContainerProxyFactory(final PicoContainer pico) { 58 if (pico == null) { 59 throw new NullPointerException (); 60 } 61 this.pico = pico; 62 } 63 64 public Object invoke(final Object proxy, final Method method, final Object [] args) throws Throwable { 65 if (method.equals(startMethod) || method.equals(stopMethod) || method.equals(disposeMethod)) { 66 throw new UnsupportedOperationException ("This container is immutable, " 67 + method.getName() 68 + " is not allowed"); 69 } else if (method.equals(equalsMethod)) { return new Boolean (args[0] != null && args[0].equals(pico)); 71 } 72 try { 73 return method.invoke(pico, args); 74 } catch (final InvocationTargetException e) { 75 throw e.getTargetException(); 76 } 77 } 78 79 89 public static PicoContainer newProxyInstance(final PicoContainer pico) { 90 return (PicoContainer)Proxy.newProxyInstance( 91 PicoContainer.class.getClassLoader(), interfaces, 92 new ImmutablePicoContainerProxyFactory(pico)); 93 } 94 } 95 | Popular Tags |