JavaSE进阶
代码演示
public interface Dog {
void info();
void run();
}
public class HuntingDog implements Dog {
public void info() {
System.out.println("我是一只猎狗");
}
public void run() {
System.out.println("我奔跑迅速");
}
}
public class DogUtil {
public void method1() {
System.out.println("=====模拟通用方法一=====");
}
public void method2() {
System.out.println("=====模拟通用方法二=====");
}
}
public class DogUtil {
public void method1() {
System.out.println("=====模拟通用方法一=====");
}
public void method2() {
System.out.println("=====模拟通用方法二=====");
}
}
public class DogUtil {
public void method1() {
System.out.println("=====模拟通用方法一=====");
}
public void method2() {
System.out.println("=====模拟通用方法二=====");
}
}
public class MyInvocationHandler implements InvocationHandler {
// 需要被代理的对象
private Object target;
public void setTarget(Object target) {
this.target = target;
}
// 执行动态代理对象的所有方法时,都会被替换成执行如下的invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
DogUtil du = new DogUtil();
// 执行DogUtil对象中的method1。
du.method1();
// 以target作为主调来执行method方法
Object result = method.invoke(target, args);
// 执行DogUtil对象中的method2。
du.method2();
return result;
}
}
public class MyInvocationHandler implements InvocationHandler {
// 需要被代理的对象
private Object target;
public void setTarget(Object target) {
this.target = target;
}
// 执行动态代理对象的所有方法时,都会被替换成执行如下的invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
DogUtil du = new DogUtil();
// 执行DogUtil对象中的method1。
du.method1();
// 以target作为主调来执行method方法
Object result = method.invoke(target, args);
// 执行DogUtil对象中的method2。
du.method2();
return result;
}
}
public class MyProxyFactory {
// 为指定target生成动态代理对象
public static Object getProxy(Object target) throws Exception {
// 创建一个MyInvokationHandler对象
MyInvokationHandler handler = new MyInvokationHandler();
// 为MyInvokationHandler设置target对象
handler.setTarget(target);
// 创建、并返回一个动态代理对象
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
}
}
public class MyProxyFactory {
// 为指定target生成动态代理对象
public static Object getProxy(Object target) throws Exception {
// 创建一个MyInvokationHandler对象
MyInvokationHandler handler = new MyInvokationHandler();
// 为MyInvokationHandler设置target对象
handler.setTarget(target);
// 创建、并返回一个动态代理对象
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
}
}
public class Test{
public static void main(String[] args)
throws Exception{
// 创建一个原始的HuntingDog对象,作为target
Dog target = new HuntingDog();
// 以指定的target来创建动态代理
Dog dog = (Dog)MyProxyFactory.getProxy(target);
dog.info();
dog.run();
}
}
- 使用Proxy生成一个动态代理时,往往并不会凭空产生一个动态代理,这样没有太大的意义。通常都是为指定的目标对象生成动态代理
- 这种动态代理在AOP中被称为AOP代理,AOP代理可代替目标对象,AOP代理包含了目标对象的全部方法。但AOP代理中的方法与目标对象的方法存在差异:AOP代理里的方法可以在执行目标方法之前、之后插入一些通用处理