1 6 7 package org.jfox.ioc.factory; 8 9 import java.lang.reflect.InvocationHandler ; 10 import java.lang.reflect.Method ; 11 import java.lang.reflect.Proxy ; 12 import java.util.HashMap ; 13 import java.util.List ; 14 import java.util.Map ; 15 16 import org.jfox.ioc.Component; 17 import org.jfox.ioc.ComponentName; 18 import org.jfox.ioc.annotation.Interceptable; 19 import org.jfox.ioc.depend.Dependency; 20 import org.jfox.ioc.exception.ComponentException; 21 import org.jfox.ioc.ext.InterceptableComponent; 22 import org.jfox.ioc.util.Annotations; 23 import org.jfox.ioc.util.Classes; 24 25 32 33 public class DynProxyComponentFactory extends ConstrComponentFactory { 34 35 public DynProxyComponentFactory(ComponentName name, Class implementation, Dependency[] params) throws ComponentException { 36 super(name,implementation,params); 37 } 38 39 46 public Component makeComponent() throws ComponentException { 47 Component comp = super.makeComponent(); 48 return (Component) Proxy.newProxyInstance(getImplementation().getClassLoader(), 49 getInterfaces(comp.getClass()), 50 new DPInvocationHandler(comp)); 51 } 52 53 59 private class DPInvocationHandler implements InvocationHandler { 60 private Component comp = null; 61 private boolean isInterceptable = false; 62 63 private Map <Method ,Boolean > methods = new HashMap <Method , Boolean >(); 64 65 public DPInvocationHandler(Component comp) { 66 this.comp = comp; 67 if(comp instanceof InterceptableComponent) { 68 isInterceptable = true; 69 } 70 } 71 72 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable { 73 boolean isMethodInterceptable = isMethodInterceptable(method); 74 if(isInterceptable && isMethodInterceptable) { 75 if(Annotations.isAnnotated(method,Interceptable.class)) { 77 ((InterceptableComponent) comp).preInvoke(method, args); 78 } 79 } 80 Object result = method.invoke(comp, args); 81 if(isInterceptable && isMethodInterceptable) { 82 if(Annotations.isAnnotated(method, Interceptable.class)) { 84 result = ((InterceptableComponent) comp).postInvoke(method, result); 85 } 86 } 87 return result; 88 } 89 90 private boolean isMethodInterceptable(Method method) throws Exception { 91 if(methods.containsKey(method)) { 92 return methods.get(method); 93 } 94 else { 95 Method concreteMethod = comp.getClass().getMethod(method.getName(),method.getParameterTypes()); 97 boolean b = Annotations.isAnnotated(concreteMethod,Interceptable.class); 98 methods.put(method,b); 99 return b; 100 } 101 } 102 } 103 104 109 private static Class [] getInterfaces(Class clazz) { 110 List interfaces = Classes.getAllInterfaces(clazz); 111 return (Class [])interfaces.toArray(new Class [interfaces.size()]); 112 } 113 114 } 115 116 | Popular Tags |