先看一下jdk的动态是怎样用的
java代码
package com.zjs.dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 实现自己的InvocationHandler
*/
public class MyInvocationHandler implements InvocationHandler{
private Object target;// 目标对象
public MyInvocationHandler(Object target){
super();// 子类的构造函数需要调用父类的构造函数
this.target = target;
}
// 执行目标对象的方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("--before--"); // 在目标对象执行前打印
Object result = method.invoke(target, args); // 执行目标对象的方法
System.out.println("--after--"); // 在目标对象的方法执行后打印
return result;
}
/**
* 获取目标对象的代理对象
* @return 代理对象
*/
public Object getProxy(){
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
target.getClass().getInterfaces(), this);
}
}
package com.zjs.Interface;
/**
* 目标对象实现的接口,用JDK 来生成代理对象一定要实现一个接口
*
*/
public interface UserService {
/**
* 目标方法
*/
public abstract void add();
}
package com.zjs.InterfaceImpl;
import com.zjs.Interface.UserService;
public class UserServiceImpl implements UserService{
public void add() {
// TODO Auto-generated method stub
System.out.println("--add--");
}
}
package com.zjs.Test;
import org.junit.Test;
import com.zjs.Interface.UserService;
import com.zjs.InterfaceImpl.UserServiceImpl;
import com.zjs.dynamic.MyInvocationHandler;
public class ProxyTest {
/**
* @param args
*/
@Test
public static void main(String[] args) {
// TODO Auto-generated method stub
UserService userService = new UserServiceImpl();// 实例化目标对象
MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);// 实例化InvocationHandler
UserService proxy = (UserService) invocationHandler.getProxy();// 根据目标对象生成代理对象
proxy.add();// 调用代理对象的方法
}
}
执行结果如下:
------------------before------------------
--------------------add---------------
-------------------after------------------
用起来是很简单吧,其实这里基本上就是AOP的一个简单实现了,在目标对象的方法执行之前和执行之后进行了增强。Spring的AOP实现其实也是用了Proxy和InvocationHandler这两个东西的。
看不懂?那就对了,研究源码一点儿一点儿扣
这里给大家提供上面代码的下载地址:http://download.csdn.net/detail/u013912973/7492685