1 16 package net.sf.cglib.proxy; 17 18 import java.io.Serializable ; 19 import java.lang.reflect.Method ; 20 import java.lang.reflect.Member ; 21 import net.sf.cglib.core.CodeGenerationException; 22 23 38 public class Proxy implements Serializable { 39 protected InvocationHandler h; 40 41 private static final CallbackFilter BAD_OBJECT_METHOD_FILTER = new CallbackFilter() { 42 public int accept(Method method) { 43 if (method.getDeclaringClass().getName().equals("java.lang.Object")) { 44 String name = method.getName(); 45 if (!(name.equals("hashCode") || 46 name.equals("equals") || 47 name.equals("toString"))) { 48 return 1; 49 } 50 } 51 return 0; 52 } 53 }; 54 55 protected Proxy(InvocationHandler h) { 56 Enhancer.registerCallbacks(getClass(), new Callback[]{ h, null }); 57 this.h = h; 58 } 59 60 private static class ProxyImpl extends Proxy { 62 protected ProxyImpl(InvocationHandler h) { 63 super(h); 64 } 65 } 66 67 public static InvocationHandler getInvocationHandler(Object proxy) { 68 if (!(proxy instanceof ProxyImpl)) { 69 throw new IllegalArgumentException ("Object is not a proxy"); 70 } 71 return ((Proxy)proxy).h; 72 } 73 74 public static Class getProxyClass(ClassLoader loader, Class [] interfaces) { 75 Enhancer e = new Enhancer(); 76 e.setSuperclass(ProxyImpl.class); 77 e.setInterfaces(interfaces); 78 e.setCallbackTypes(new Class []{ 79 InvocationHandler.class, 80 NoOp.class, 81 }); 82 e.setCallbackFilter(BAD_OBJECT_METHOD_FILTER); 83 e.setUseFactory(false); 84 return e.createClass(); 85 } 86 87 public static boolean isProxyClass(Class cl) { 88 return cl.getSuperclass().equals(ProxyImpl.class); 89 } 90 91 public static Object newProxyInstance(ClassLoader loader, Class [] interfaces, InvocationHandler h) { 92 try { 93 Class clazz = getProxyClass(loader, interfaces); 94 return clazz.getConstructor(new Class []{ InvocationHandler.class }).newInstance(new Object []{ h }); 95 } catch (RuntimeException e) { 96 throw e; 97 } catch (Exception e) { 98 throw new CodeGenerationException(e); 99 } 100 } 101 } 102 | Popular Tags |