动态,指的是代理类实在程序运行时创建的,而不是在程序运行前手动编码来定义代理类的。这些动态代理类是在运行时候根据我们在JAVA代码中的“指示”动态生成的。动态代理的使用方式呢,主要就是分为两种:一种是基于接口的代理;另一种则是基于类的代理。

基于接口的代理,就是jdk自带的动态代理规则的实现方式,后者则是基于一些字节类增强的类代理,如cglib,javassist等。
jdk代理最主要的就是三个类:目标接口,目标类(实现了目标接口),扩展处理器InvocationHandler类。

1.创建被代理的接口和类

//目标接口
public interface HelloInterfece {
    public void sayHello();
}

//目标类
public class HelloInterfeceImpl implements HelloInterfecr {
    @Override
    public void sayHello() {
        System.out.println("say..hello...");
    }
}

//扩展处理器
2.创建代理类实现InvocationHandler 接口
public class HelloProxy implements InvocationHandler {
    private Object target;
    public HelloProxy(Object target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("----代理前----");
        Object result=method.invoke(target,args);
        System.out.println("-----代理后----");
        return result;
    }
}

3.编写测试类
public class HelloProxyTest {

    public static void main(String[] args) {
        //实例化被代理对象
        HelloInterfecr helloInterfece = new HelloInterfeceImpl();
        //实例化代理对象
        HelloProxy helloProxy = new HelloProxy(helloInterfece);
        //建立代理关系
        HelloInterfecr helloInterfeceImpl = (HelloInterfecr) Proxy.newProxyInstance(helloInterfece.getClass().getClassLoader(), helloInterfece.getClass().getInterfaces(), helloProxy);
        //调用方法
        helloInterfeceImpl.sayHello();
    }
}

01-12 22:06