java之动态代理设计模式

时间:2022-04-16 16:11:19

代理:专门完成代理请求的操作类,是所有动态代理类的父类,通过此类为一个或多个接口动态地生成实现类

弄清动态代理的关键是清楚java的反射机制,在https://www.cnblogs.com/xiximayou/p/12073611.html中已作详细说明。

具体实例:通过动态代理为TestProxy接口生成相应的实现类。

TestProxy.java

package Prox;

public interface TestProxy {
public void test1();
public void test2();
}

TestProxyImpl.java

package Prox;

public class TestProxyImpl implements TestProxy {

    @Override
public void test1() {
// TODO Auto-generated method stub
System.out.println("执行test1");
} @Override
public void test2() {
// TODO Auto-generated method stub
System.out.println("执行test2");
} }

ProxyDemo.java

package Prox;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method; //这是动态代理类
public class ProxyDemo implements InvocationHandler{ //被代理的对象
Object obj;
public ProxyDemo(Object obj) {
this.obj = obj;
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
//这里指定代理对象的执行方法
System.out.println(method.getName()+"方法开始执行");
Object result = method.invoke(this.obj,args);
System.out.println(method.getName()+"方法结束执行");
return result;
} }

Test.java

package Prox;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy; public class Test {
public static void main(String[] args) {
TestProxy testProxy = new TestProxyImpl();
testProxy.test1();
testProxy.test2();
InvocationHandler handler = new ProxyDemo(testProxy);
//第一个参数是handler.getClass().getClassLoader()类加载器
//第二个参数是被代理对象的接口
//第三个参数是代理的对象
//返回值就是被成功代理后的对象
TestProxy tp = (TestProxy) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
testProxy.getClass().getInterfaces(), handler);
System.out.println("---------------");
tp.test1();
System.out.println("---------------");
tp.test2();
System.out.println("---------------");
} }

输出:

执行test1
执行test2
---------------
test1方法开始执行
执行test1
test1方法结束执行
---------------
test2方法开始执行
执行test2
test2方法结束执行
---------------