1 54 package org.logicalcobwebs.cglib.proxy; 55 56 import java.io.Serializable ; 57 import java.lang.reflect.Method ; 58 import java.lang.reflect.Member ; 59 import org.logicalcobwebs.cglib.core.CodeGenerationException; 60 61 76 public class Proxy implements Serializable { 77 protected InvocationHandler h; 78 79 private static final CallbackFilter BAD_OBJECT_METHOD_FILTER = new CallbackFilter() { 80 public int accept(Method method) { 81 if (method.getDeclaringClass().getName().equals("java.lang.Object")) { 82 String name = method.getName(); 83 if (!(name.equals("hashCode") || 84 name.equals("equals") || 85 name.equals("toString"))) { 86 return 1; 87 } 88 } 89 return 0; 90 } 91 }; 92 93 protected Proxy(InvocationHandler h) { 94 EnhancerEmitter.setThreadCallbacks(getClass(), new Callback[]{ h, null }); 95 this.h = h; 96 } 97 98 private static class ProxyImpl extends Proxy { 100 protected ProxyImpl(InvocationHandler h) { 101 super(h); 102 } 103 } 104 105 public static InvocationHandler getInvocationHandler(Object proxy) { 106 if (!(proxy instanceof ProxyImpl)) { 107 throw new IllegalArgumentException ("Object is not a proxy"); 108 } 109 return ((Proxy)proxy).h; 110 } 111 112 public static Class getProxyClass(ClassLoader loader, Class [] interfaces) { 113 Enhancer e = new Enhancer(); 114 e.setSuperclass(ProxyImpl.class); 115 e.setInterfaces(interfaces); 116 e.setCallbackTypes(new Class []{ 117 InvocationHandler.class, 118 NoOp.class, 119 }); 120 e.setCallbackFilter(BAD_OBJECT_METHOD_FILTER); 121 e.setUseFactory(false); 122 return e.createClass(); 123 } 124 125 public static boolean isProxyClass(Class cl) { 126 return cl.getSuperclass().equals(ProxyImpl.class); 127 } 128 129 public static Object newProxyInstance(ClassLoader loader, Class [] interfaces, InvocationHandler h) { 130 try { 131 Class clazz = getProxyClass(loader, interfaces); 132 return clazz.getConstructor(new Class []{ InvocationHandler.class }).newInstance(new Object []{ h }); 133 } catch (RuntimeException e) { 134 throw e; 135 } catch (Exception e) { 136 throw new CodeGenerationException(e); 137 } 138 } 139 } 140 | Popular Tags |