动态,指的是代理类实在程序运行时建立的,而不是在程序运行前手动编码来定义代理类的。这些动态代理类是在运行时候根据咱们在JAVA代码中的“指示”动态生成的。动态代理的使用方式呢,主要就是分为两种:一种是基于接口的代理;另外一种则是基于类的代理。java
基于接口的代理,就是jdk自带的动态代理规则的实现方式,后者则是基于一些字节类加强的类代理,如cglib,javassist等。
jdk代理最主要的就是三个类:目标接口,目标类(实现了目标接口),扩展处理器InvocationHandler类。ide
1.建立被代理的接口和类测试
//目标接口
public interface HelloInterfece {
public void sayHello();
}this
//目标类
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;
}
}.net
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();
}
}对象