动态代理一直停留理论了解写个小demo加深理解
动态代理:代理的对象是动态的利用反射的方式实现
1.接口
2.实现类实现接口
3.InvocationHandlerImpl 实现InvocationHandler 重写invoke
4.接口实现类通过InvocationHandlerImpl 将对应接口进行代理
动态代理代理的是接口
package com.zhuning.isim.gateway.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @Date 2021/4/6 11:03
* @Created by gaoyuanfeng
*/
// 接口
interface Interface {
String method1(String a);
}
//实现类
class Impl implements Interface {
@Override
public String method1(String a) {
return a;
}
}
// 调用处理器实现类 每次生成动态代理类对象时都需要指定一个实现了该接口的调用处理器对象
class InvocationHandlerImpl implements InvocationHandler {
private Object object;
public InvocationHandlerImpl(Object obj) {
this.object = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(this.object, args);
}
}
public class test {
public static void main(String[] args) {
Impl impl = new Impl();
InvocationHandlerImpl invocationHandler = new InvocationHandlerImpl(impl);
//必须是接口 动态代理代理的是接口 如果是实现类会出现异常 Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast
Interface interfaceClass = (Interface) Proxy.newProxyInstance(Impl.class.getClassLoader(), Impl.class.getInterfaces(), invocationHandler);
// 接口调用方法
String s = interfaceClass.method1("AAA");
System.out.println(s);
}
}