import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class JDKProxy {
/**
* jdk 动态代理:基于接口,动态代理类需要再运行时指定所代理对象实现的接口,客户端在调用动态代理对象的方法
* 时,调用请求会将请求自动转发给 InvocationHandler对象的invoke()方法,由invoke()方法来实现
* 对请求的统一处理
* 1.创建一个接口subject
* 2.创建一个需要被代理的对象,对象实现subject
* 3.创建 invoactionHandler 对象,该对象有一个Object属性,用于接收需要被代理的真实对象,
* 该接口作为代理实列的调用处理类
* 4.创建需要被代理的对象,将该对象传入 invocationHandler中
* 5.使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
* 在 Proxy.newProxyInstance 中,首先通过 ProxyClassFactory 对象的generateClassFile()方法获取接口信息,生成 byte[] .class字节码文件;
* 然后将字节码文件加载到 JVM 中,最后创建通过 instance 创建对象
* 返回一个Class类型的代理类,在参数中需要提供类加载器并需要指定代理的接口数组(与真实代理对象实现的接口列表一致)
*/
public static void main(String[] args) {
JDKEntryInterface entry = new JDKEntry("LiXiaolong");
InvocationHandler handler = new JDKInvocationHandler();
((JDKInvocationHandler) handler).setObject(entry);
JDKEntryInterface proxy = (JDKEntryInterface) Proxy.newProxyInstance(
JDKEntryInterface.class.getClassLoader(),
new Class[]{ JDKEntryInterface.class },
handler
);
proxy.exercise();
}
}
1.创建一个接口
public interface JDKEntryInterface {
void exercise();
}
2.创建一个需要被代理的对象,对象实现1步骤的接口
public class JDKEntry implements JDKEntryInterface {
private String name;
public JDKEntry(String name){
this.name = name;
}
@Override
public void exercise() {
System.out.println("my name is " + name + ". I want to exercise");
}
}
3.创建invoactionHandler对象,该对象拥有一个Object(也可以是要进行代理对象的引用)类型的属性,用于接收需要被代理的真实对象
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class JDKInvocationHandler implements InvocationHandler {
private Object object;
public void setObject(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("---------执行前动作-----------");
Object result = method.invoke(this.object, args);
System.out.println("---------执行后动作-----------");
return result;
}
}
4.创建需要被代理的对象,将该对象传入 invocationHandler中
// 创建需要代理的实体类
JDKEntryInterface entry = new JDKEntry("LiXiaolong");
// 创建InvocationHandler对象
InvocationHandler handler = new JDKInvocationHandler();
// 传参
((JDKInvocationHandler) handler).setObject(entry);
5.使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)返回一个Class类型的代理类,在参数中需要提供类加载器并需要指定代理的接口数组(与真实代理对象实现的接口列表一致)
JDKEntryInterface proxy = (JDKEntryInterface) Proxy.newProxyInstance(
JDKEntryInterface.class.getClassLoader(),
new Class[]{ JDKEntryInterface.class },
handler
);
6.执行实体对象方法
proxy.exercise();
7.执行结果
---------执行前动作-----------
my name is LiXiaolong. I want to exercise
---------执行后动作-----------