1 package tests.jfun.models; 2 3 import java.lang.reflect.InvocationHandler ; 4 import java.lang.reflect.Method ; 5 import java.lang.reflect.Proxy ; 6 7 public class InjectingDecorator implements InvocationHandler { 8 private final Injector injector; 9 private final Class target_type; 10 private final Object self; 11 12 private InjectingDecorator(Object self, Class target_type, Injector injector) { 13 this.injector = injector; 14 this.self = self; 15 this.target_type = target_type; 16 } 17 public Object invoke(Object proxy, Method mtd, Object [] args) 18 throws Throwable { 19 if(Object .class.equals(mtd.getDeclaringClass())){ 20 return mtd.invoke(this, args); 21 } 22 else{ 23 final Object r = mtd.invoke(self, args); 24 if(target_type.isInstance(r)){ 25 injector.inject(r); 27 } 28 return r; 29 } 30 } 31 public boolean equals(Object obj) { 32 if(obj == null) return false; 33 if(Proxy.isProxyClass(obj.getClass())){ 34 obj = Proxy.getInvocationHandler(obj); 35 } 36 if(obj instanceof InjectingDecorator){ 37 final InjectingDecorator other = (InjectingDecorator)obj; 38 return self.equals(other.self); 39 } 40 else return self.equals(obj); 41 } 42 public int hashCode() { 43 return self.hashCode(); 44 } 45 public String toString() { 46 return self.toString(); 47 } 48 public static Object getInjectingDecorator(ClassLoader cloader, Class [] itfs, 49 Object self, Class injectee_type, Injector injector){ 50 return Proxy.newProxyInstance(cloader, itfs, 51 new InjectingDecorator(self, injectee_type, injector)); 52 } 53 public static Object getInjectingDecorator(ClassLoader cloader, Class itf, 54 Object self, Class injectee_type, Injector injector){ 55 return getInjectingDecorator(cloader, new Class []{itf}, self, injectee_type, injector); 56 } 57 public static Object getInjectingDecorator(Class itf, Object self, Class injectee_type, Injector injector){ 58 return getInjectingDecorator(injectee_type.getClassLoader(), itf, self, injectee_type, injector); 59 } 60 public static Object getInjectingDecorator(Object self, Class injectee_type, Injector injector){ 61 final Class [] itfs = self.getClass().getInterfaces(); 62 return getInjectingDecorator(injectee_type.getClassLoader(), itfs, 63 self, injectee_type, injector); 64 } 65 } 66 | Popular Tags |