public class LogProxy implements InvocationHandler { private Object object; public LogProxy(Object object) { super(); this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(this.object, args); System.out.println("记录到数据库.."); return null; } public void setObject(Object object) { this.object = object; } public Object getObject() { return object; } } public class PowerProxy implements InvocationHandler { private Object object; public PowerProxy(Object object) { super(); this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("进行权限验证..是否是黑名单.."); method.invoke(this.object, args); return null; } public void setObject(Object object) { this.object = object; } public Object getObject() { return object; } }
public class Client { /** * @Title: main * @Description: TODO(这里用一句话描述这个方法的作用) * @param args 描述 * @return void 返回类型 * @throws */ public static void main(String[] args) { Person zhangsan = new Person("张三"); Zegapain jiqiren = new Zegapain("编号89757"); Speakable zhangsanProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new LogProxy(zhangsan)); Speakable jiqirenProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new LogProxy(jiqiren)); zhangsanProxy.speak("呵呵"); jiqirenProxy.speak("您好,我是机器人"); System.out.println("----------------------------"); Speakable zhangsanPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(zhangsan)); zhangsanPowerProxy.speak("我不是坏人"); System.out.println("----------------------------"); Speakable jiqirenPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(jiqirenProxy)); jiqirenPowerProxy.speak("我是您的机器人"); } }
Speakable zhangsanPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(zhangsan));
TestProxy tp = new TestProxy(); zhangsan= (Person ) tp.getProxy(Person.class);
Class cl = getProxyClass(loader, interfaces);
if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); }
Class proxyClass = null; /* collect interface names to use as key for proxy class cache */ String[] interfaceNames = new String[interfaces.length]; Set interfaceSet = new HashSet(); // for detecting duplicates for (int i = 0; i < interfaces.length; i++) { /* * Verify that the class loader resolves the name of this * interface to the same Class object. */ String interfaceName = interfaces[i].getName(); Class interfaceClass = null; try { interfaceClass = Class.forName(interfaceName, false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != interfaces[i]) { throw new IllegalArgumentException( interfaces[i] + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. */ if (!interfaceClass.isInterface()) { throw new IllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. */ if (interfaceSet.contains(interfaceClass)) { throw new IllegalArgumentException( "repeated interface: " + interfaceClass.getName()); } interfaceSet.add(interfaceClass); interfaceNames[i] = interfaceName; }
Map cache; synchronized (loaderToCache) { cache = (Map) loaderToCache.get(loader); if (cache == null) { cache = new HashMap(); loaderToCache.put(loader, cache); } /* * This mapping will remain valid for the duration of this * method, without further synchronization, because the mapping * will only be removed if the class loader becomes unreachable. */ } /* * Look up the list of interfaces in the proxy class cache using * the key. This lookup will result in one of three possible * kinds of values: * null, if there is currently no proxy class for the list of * interfaces in the class loader, * the pendingGenerationMarker object, if a proxy class for the * list of interfaces is currently being generated, * or a weak reference to a Class object, if a proxy class for * the list of interfaces has already been generated. */ synchronized (cache) { /* * Note that we need not worry about reaping the cache for * entries with cleared weak references because if a proxy class * has been garbage collected, its class loader will have been * garbage collected as well, so the entire cache will be reaped * from the loaderToCache map. */ do { Object value = cache.get(key); if (value instanceof Reference) { proxyClass = (Class) ((Reference) value).get(); } if (proxyClass != null) { // proxy class already generated: return it return proxyClass; } else if (value == pendingGenerationMarker) { // proxy class being generated: wait for it try { cache.wait(); } catch (InterruptedException e) { /* * The class generation that we are waiting for should * take a small, bounded time, so we can safely ignore * thread interrupts here. */ } continue; } else { /* * No proxy class for this list of interfaces has been * generated or is being generated, so we will go and * generate it now. Mark it as pending generation. */ cache.put(key, pendingGenerationMarker); break; } } while (true); }
String proxyPkg = null; String proxyPkg = null; // package to define proxy class in /* * Record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. Verify that * all non-public proxy interfaces are in the same package. */ for (int i = 0; i < interfaces.length; i++) { int flags = interfaces[i].getModifiers(); if (!Modifier.isPublic(flags)) { String name = interfaces[i].getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } else if (!pkg.equals(proxyPkg)) { throw new IllegalArgumentException( "non-public interfaces from different packages"); } } } if (proxyPkg == null) { // if no non-public proxy interfaces, proxyPkg = ""; // use the unnamed package } // package to define proxy class in /* * Record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. Verify that * all non-public proxy interfaces are in the same package. */ for (int i = 0; i < interfaces.length; i++) { int flags = interfaces[i].getModifiers(); if (!Modifier.isPublic(flags)) { String name = interfaces[i].getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } else if (!pkg.equals(proxyPkg)) { throw new IllegalArgumentException( "non-public interfaces from different packages"); } } } if (proxyPkg == null) { // if no non-public proxy interfaces, proxyPkg = ""; // use the unnamed package }
long num; synchronized (nextUniqueNumberLock) { num = nextUniqueNumber++; } String proxyName = proxyPkg + proxyClassNamePrefix + num;
byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces); try { proxyClass = defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { /* * A ClassFormatError here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded). */ throw new IllegalArgumentException(e.toString()); } } // add to set of all generated proxy classes, for isProxyClass proxyClasses.put(proxyClass, null); } finally { /* * We must clean up the "pending generation" state of the proxy * class cache entry somehow. If a proxy class was successfully * generated, store it in the cache (with a weak reference); * otherwise, remove the reserved entry. In all cases, notify * all waiters on reserved entries in this cache. */ synchronized (cache) { if (proxyClass != null) { cache.put(key, new WeakReference(proxyClass)); } else { cache.remove(key); } cache.notifyAll(); } } return proxyClass; }
Constructor cons = cl.getConstructor(constructorParams); return (Object) cons.newInstance(new Object[] { h });
参考:
《spring 3.x 企业级应用程序开发实战》
http://www.cnblogs.com/frankliiu-java/articles/1896443.html