动态代理
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7d1ab149e9af839b69b9585ff56568e3.png#pic_center)
@startuml
note top of Proxy
Proxy 代理类
Object proxy = (Object)Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
通过Proxy类的newProxyInstance方法创建代理对象,我们来看下方法中的参数
第一个参数:people.getClass().getClassLoader(),使用handler对象的classloader对象来加载我们的代理对象
第二个参数:people.getClass().getInterfaces(),这里为代理类提供的接口是真实对象实现的接口,这样代理对象就能像真实对象一样调用接口中的所有方法
第三个参数:handler,我们将代理对象关联到上面的InvocationHandler对象上
end note
class Proxy implements Serializable{
+ Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
Proxy +-- InvocationHandler
note top of InvocationHandler : 实现InvocationHandler接口,重写invoke方法。
interface InvocationHandler{
+ Object invoke(Object proxy, Method method, Object[] args)
}
note top of Enhancer
cglib Enhancer 代理 </br>
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(SampleClass.class);
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("before method run...");
Object result = proxy.invokeSuper(obj, args);
System.out.println("after method run...");
return result;
]}
});
SampleClass sample = (SampleClass) enhancer.create();
sample.test();
end note
class Enhancer extends AbstractClassGenerator{
- Class superclass
- Callback[] callbacks
+ void setSuperclass(Class superclass)
+ void setCallback(Callback callback)
+ Object create()
- Object createHelper()
# void setNamePrefix(String namePrefix)
# Object firstInstance(Class type)
# Object nextInstance(Object instance)
}
abstract class AbstractClassGenerator implements ClassGenerator{
# Object create(Object key)
# abstract Object firstInstance(Class var1)
# abstract Object nextInstance(Object var1)
}
interface ClassGenerator{
+ generateClass(ClassVisitor var1)
}
Enhancer +-- Callback
interface Callback{}
interface MethodInterceptor extends Callback{
+ Object intercept(Object var1, Method var2, Object[] var3, MethodProxy var4)
}
Enhancer +-- Class
interface Class{}
interface Serializable{}
@enduml