1 17 package org.apache.avalon.excalibur.component; 18 19 import java.lang.reflect.InvocationHandler ; 20 import java.lang.reflect.InvocationTargetException ; 21 import java.lang.reflect.Method ; 22 import java.lang.reflect.Proxy ; 23 24 import java.util.HashSet ; 25 import java.util.Set ; 26 27 import org.apache.avalon.framework.component.Component; 28 29 36 public final class ComponentProxyGenerator 37 { 38 private final ClassLoader m_classLoader; 39 40 44 public ComponentProxyGenerator() 45 { 46 this( Thread.currentThread().getContextClassLoader() ); 47 } 48 49 54 public ComponentProxyGenerator( final ClassLoader parentClassLoader ) 55 { 56 m_classLoader = ( null == parentClassLoader ) ? 57 ( ( null == Thread.currentThread().getContextClassLoader() ) ? 58 getClass().getClassLoader() 59 : Thread.currentThread().getContextClassLoader() ) 60 : parentClassLoader; 61 } 62 63 67 public Component getProxy( String role, Object service ) throws Exception 68 { 69 if( role.indexOf( '/' ) != -1 ) 71 { 72 role = role.substring( 0, role.indexOf( '/' ) ); 73 } 74 75 Class serviceInterface = m_classLoader.loadClass( role ); 76 77 return (Component)Proxy.newProxyInstance( m_classLoader, 78 new Class []{Component.class, serviceInterface}, 79 new ComponentInvocationHandler( service ) ); 80 } 81 82 87 public Component getCompatibleProxy( Object service ) throws Exception 88 { 89 Set interfaces = new HashSet (); 90 getAllInterfaces( service.getClass(), interfaces ); 91 92 interfaces.add( Component.class ); 93 94 Class [] proxyInterfaces = (Class []) interfaces.toArray( new Class [0] ); 95 96 return (Component)Proxy.newProxyInstance( m_classLoader, 97 proxyInterfaces, 98 new ComponentInvocationHandler( service ) ); 99 } 100 101 private void getAllInterfaces( Class clazz, Set interfaces ) throws Exception 102 { 103 if (clazz == null) 104 { 105 return; 106 } 107 108 Class [] objectInterfaces = clazz.getInterfaces(); 109 for( int i = 0; i < objectInterfaces.length; i++ ) 110 { 111 interfaces.add( objectInterfaces[i] ); 112 } 113 114 getAllInterfaces( clazz.getSuperclass(), interfaces ); 115 } 116 117 118 121 private final static class ComponentInvocationHandler 122 implements InvocationHandler 123 { 124 private final Object m_delagate; 125 126 public ComponentInvocationHandler( final Object delegate ) 127 { 128 if( null == delegate ) 129 { 130 throw new NullPointerException ( "delegate" ); 131 } 132 133 m_delagate = delegate; 134 } 135 136 public Object invoke( final Object proxy, 137 final Method meth, 138 final Object [] args ) 139 throws Throwable 140 { 141 try 142 { 143 return meth.invoke( m_delagate, args ); 144 } 145 catch( final InvocationTargetException ite ) 146 { 147 throw ite.getTargetException(); 148 } 149 } 150 } 151 } 152 | Popular Tags |