文章出自:
http://rejoy.iteye.com/blog/1627405?page=2#comments
http://langyu.iteye.com/blog/410071
和动态代理有关的有两个类
1.interface InvocationHandler
Object invoke(Object proxy, Method method, Object[] args)
2.class Proxy
真正表示动态代理的类,提供两个静态方法:
Class<?> getProxyClass(ClassLoader loader, Class<?>[] interface)
用来产生代理类,参数要提供interface数组,它会生成这些interface的“虚拟实现”,
用来冒充真实的对象。
Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
产生代理对象,多了InvocationHandler参数(只是InvocationHandler接口的实现类),
它与代理对象关联,当请求分发到代理对象后,会自动执行h.invoke(...)方法,
invoke方法就是我们用来做N多事情的地方 -_-。
利用JDK实现动态代理的例子如下:
Hello.java
- package com.yusj.service;
-
-
-
-
-
-
- public interface Hello {
-
-
-
-
-
- public abstract void sayHello(String say) ;
-
-
-
-
-
- public abstract void pring(String str) ;
- }
HelloImpl.java
- package com.yusj.service.impl;
-
- import com.yusj.service.Hello;
-
-
-
-
-
- public class HelloImpl implements Hello {
-
-
-
- @Override
- public void sayHello(String say) {
- System.out.println("Say hello to "+say) ;
- }
-
-
-
-
- @Override
- public void pring(String str) {
- System.out.println("pring : "+str) ;
- }
- }
MyInvocationHandler.java
- package com.yusj.proxy;
-
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
-
-
-
-
-
-
- public class MyInvocationHandler implements InvocationHandler {
-
-
- private Object target ;
-
-
-
-
-
- public MyInvocationHandler(Object target) {
- super() ;
- this.target = target ;
- }
-
-
-
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
-
-
- doBefore();
-
-
- Object result = method.invoke(target, args) ;
-
-
- after();
-
- return result;
- }
-
-
-
-
-
- public Object getProxy(){
- return Proxy.newProxyInstance(Hello.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
- }
-
- private void doBefore() {
- System.out.println("before....");
- }
-
- private void after() {
- System.out.println("after....");
- }
-
- }
Test.java
- package com.yusj.test;
-
- import com.yusj.proxy.MyInvocationHandler;
- import com.yusj.service.Hello;
- import com.yusj.service.impl.HelloImpl;
-
-
-
-
-
-
- public class Test {
-
- public static void main(String[] args) {
-
- Hello h = new HelloImpl() ;
-
-
- MyInvocationHandler myInvocationHandler = new MyInvocationHandler(h);
-
-
- Hello proxy = (Hello)myInvocationHandler.getProxy();
-
-
- proxy.sayHello("张三");
- proxy.pring("大家好");
-
-
-
-
-
-
-
-
-
-
- }
-
- }
用起来是很简单吧,其实这里基本上就是AOP的一个简单实现了,在目标对象的方法执行之前和执行之后进行了增强。Spring的AOP实现其实也是用了Proxy和InvocationHandler这两个东西的。
用起来是比较简单,但是如果能知道它背后做了些什么手脚,那就更好不过了。首先来看一下JDK是怎样生成代理对象的。既然生成代理对象是用的Proxy类的静态方newProxyInstance,那么我们就去它的源码里看一下它到底都做了些什么?
-
-
-
-
-
- public static Object newProxyInstance(ClassLoader loader,
- Class<?>[] interfaces,
- InvocationHandler h)
- throws IllegalArgumentException
- {
- if (h == null) {
- throw new NullPointerException();
- }
-
-
-
-
- Class cl = getProxyClass(loader, interfaces);
-
-
-
-
- try {
-
- Constructor cons = cl.getConstructor(constructorParams);
-
- return (Object) cons.newInstance(new Object[] { h });
- } catch (NoSuchMethodException e) {
- throw new InternalError(e.toString());
- } catch (IllegalAccessException e) {
- throw new InternalError(e.toString());
- } catch (InstantiationException e) {
- throw new InternalError(e.toString());
- } catch (InvocationTargetException e) {
- throw new InternalError(e.toString());
- }
- }
我们再进去getProxyClass方法看一下
- public static Class<?> getProxyClass(ClassLoader loader,
- Class<?>... interfaces)
- throws IllegalArgumentException
- {
-
- if (interfaces.length > 65535) {
- throw new IllegalArgumentException("interface limit exceeded");
- }
-
-
- Class proxyClass = null;
-
- String[] interfaceNames = new String[interfaces.length];
-
- Set interfaceSet = new HashSet();
-
-
- for (int i = 0; i < interfaces.length; i++) {
-
-
- 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");
- }
-
-
-
-
- interfaceSet.add(interfaceClass);
-
- interfaceNames[i] = interfaceName;
- }
-
-
- Object key = Arrays.asList(interfaceNames);
-
- Map cache;
-
- synchronized (loaderToCache) {
-
- cache = (Map) loaderToCache.get(loader);
- if (cache == null) {
-
- cache = new HashMap();
-
- loaderToCache.put(loader, cache);
- }
-
- }
-
- synchronized (cache) {
-
- do {
-
- Object value = cache.get(key);
- if (value instanceof Reference) {
- proxyClass = (Class) ((Reference) value).get();
- }
- if (proxyClass != null) {
-
- return proxyClass;
- } else if (value == pendingGenerationMarker) {
- try {
- cache.wait();
- } catch (InterruptedException e) {
- }
- continue;
- } else {
- cache.put(key, pendingGenerationMarker);
- break;
- }
- } while (true);
- }
-
- try {
-
-
-
- byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
- proxyName, interfaces);
- try {
-
- proxyClass = defineClass0(loader, proxyName,
- proxyClassFile, 0, proxyClassFile.length);
- } catch (ClassFormatError e) {
- throw new IllegalArgumentException(e.toString());
- }
- }
-
- proxyClasses.put(proxyClass, null);
-
- }
-
-
- return proxyClass;
- }
进去ProxyGenerator类的静态方法generateProxyClass,这里是真正生成代理类class字节码的地方。
- public static byte[] generateProxyClass(final String name,
- Class[] interfaces)
- {
- ProxyGenerator gen = new ProxyGenerator(name, interfaces);
-
- final byte[] classFile = gen.generateClassFile();
-
-
- if (saveGeneratedFiles) {
- java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction<Void>() {
- public Void run() {
- try {
- FileOutputStream file =
- new FileOutputStream(dotToSlash(name) + ".class");
- file.write(classFile);
- file.close();
- return null;
- } catch (IOException e) {
- throw new InternalError(
- "I/O exception saving generated file: " + e);
- }
- }
- });
- }
-
-
- return classFile;
- }
现在,JDK是怎样动态生成代理类的字节的原理已经一目了然了。