- 两个重点: Proxy类和InvocationHandler接口
1.定义接口
2.定义动态代理的对象,该对象实现接口
3.定义通用方法的类,该类中定义通用方法(例如记录开始日志方法,结束日志方法)
4.定义实现InvocationHandler的方法(调用通用方法,使用反射调用被代理对象的方法)
5.定义动态代理对象工厂类,即根据target生成动态代理对象
6.测试
public interface Dog {
void info();
void run();
}
public class DogUtil {
public void method1(){
System.out.println("模拟第一个通用方法");
}
public void method2(){
System.out.println("模拟第二个通用方法");
}
}
public class GunDog implements Dog{
@Override
public void info() {
System.out.println("我是只猎狗!");
}
@Override
public void run() {
System.out.println("我跑的很快!");
}
}
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
@Override
public java.lang.Object invoke(java.lang.Object proxy, Method method, java.lang.Object[] args) throws Throwable {
DogUtil du = new DogUtil();
du.method1();
java.lang.Object result=method.invoke(target,args);
du.method2();
return result;
}
}
public class MyProxyFactory {
public static java.lang.Object getProxy(Object target){
MyInvocationHandler handler = new MyInvocationHandler();
handler.setTarget(target);
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
}
}
public class MyProxyTest {
public static void main(String[] args) {
Dog target = new GunDog();
Dog dog = (Dog)MyProxyFactory.getProxy(target);
dog.info();
dog.run();
}
}