动态代理例子程序结构截图
1).TimeHandler.java 代理处理类
(此类是实现动态代理的核心处理类,需要实现java.lang.reflect反射包中的InvocationHandler接口)
package handler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
//代理类需要实现InvocationHandler接口,并重写invoke方法
public class TimeHandler implements InvocationHandler{
private Object target;
//target:被代理对象,也就是StudentService类对象
public TimeHandler(Object target){
this.target = target;
}
//obj:代理类对象
//method:调用的业务处理方法,这里是saveStu()方法
//args:方法所需参数
@Override
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
System.out.println("begin!!!");
//调用saveStu()业务处理方法
Object rval = method.invoke(target, args);
System.out.println("end!!!");
return rval;
}
}
2)StudentServiceImpl.java 业务处理实现类
(就是平时最普通的业务处理实现类,没有特别之处)
package stu.impl;
import stu.StudentService;
public class StudenServiceImpl implements StudentService {
public void saveStu(){
System.out.println("stu saved!!!");
}
}
3)StudentService.java 业务处理接口类
(就是平时最普通的业务处理接口类,没有特别之处)
package stu;
public interface StudentService {
public void saveStu();
}
4)Main.java 程序入口方法类
import handler.TimeHandler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import stu.StudentService;
import stu.impl.StudenServiceImpl;
public class Main {
public static void main(String[] args) {
StudentService stu = new StudenServiceImpl();
//创建TimeHandler实例对象
InvocationHandler td = new TimeHandler(stu);
//调用Proxy类newProxyInstance方法创建代理对象,将代理对象强制装换为StudentService对象
StudentService stuProxy = (StudentService)Proxy.newProxyInstance(stu.getClass().getClassLoader(),new Class<?>[]{StudentService.class},td);
stuProxy.saveStu();
}
}