前言
Java标准库提供了一种动态代理(Dynamic Proxy)的机制,可以在运行期动态创建某个interface
的实例,故不编写实现类,也可以直接在运行期创建某个interface
的实例。
正常情况下创建interface实现类的示例
创建接口
public interface YunYun {
void sayHello(String string);
}
创建实现类
public class YunYunSayHello implements YunYun{
public void sayHello(String string){
System.out.println("i am "+string+"pig");
}
}
最后在main方法中得到YunYunSayHello的实例对象并调用sayHello方法即可。
动态代理
创建接口
public interface YunYun {
void sayHello(String string);
}
创建handler类来实现InvocationHandler接口
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyYunYunHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName());
if (method.getName().equals("sayHello")){
System.out.println("允允是 " + args[0]+"的猪");
}
return null;
}
}
测试类
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
ProxyYunYunHandler proxyYunYunHandler=new ProxyYunYunHandler();
//newProxyInstance()该方法需要3个参数:
//ClassLoader,通常就是接口类的ClassLoader;
//需要实现的接口数组,至少需要传入一个接口进去;
//InvocationHandler接口的实现类的对象实例。
YunYun yunyun =(YunYun) Proxy.newProxyInstance(YunYun.class.getClassLoader(),new Class[]{YunYun.class},proxyYunYunHandler);
yunyun.sayHello("300斤");
}
}
结果:
运行期动态创建一个interface
实例过程:
- 创建一个
InvocationHandler接口的实现类。
- 通过
Proxy.newProxyInstance()
创建interface
实例,该方法需要3个参数:ClassLoader
,通常就是接口类的ClassLoader
;- 需要实现的接口数组,至少需要传入一个接口进去;
InvocationHandler接口的实现类的对象
实例。
- 将返回的
Object
强转为所需的接口。
生成代理对象时,用的是Proxy类中的newProxyInstance()方法,newProxyInstance()方法、直接生成代理类字节码,并解析代理类字节码然后生成代理类Class对象。
基于 https://www.liaoxuefeng.com/wiki/1252599548343744/1264804593397984 创作