JDK动态代理
使用JDK代理
被代理的接口类
public interface TargetInterface {
void function();
}
被代理的类
public class Target implements TargetInterface{
@Override
public void function() {
System.out.println("方法执行");
}
}
测试
public class JDKProxyTest {
public static void main(String[] args) {
//在项目根目录生成class字节文件
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
//被代理的类
Target target = new Target();
//创建接口代理类
TargetInterface targetProxy = (TargetInterface) Proxy.newProxyInstance(Target.class.getClassLoader(), new Class[]{TargetInterface.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法执行前增强,方法名:"+ method.getName());
//反射调用被代理的类
method.invoke(target,args);
System.out.println("方法执行后增强----------");
return null;
}
});
targetProxy.function();
}
}
看一下这个proxy类
public class Proxy implements java.io.Serializable {
private static final long serialVersionUID = -2222568056686623797L;
private static final Class<?>[] constructorParams = { InvocationHandler.class };
/**
* 代理类的缓存
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
protected InvocationHandler h;
//省略代码
}
在Proxy.newProxyInstance的方法中先获得代理类
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h) throws IllegalArgumentException {
//省略代码
//获得代理类
Class<?> cl = getProxyClass0(loader, intfs);
//省略代码
//获得构造方法
final Constructor<?> cons = cl.getConstructor(constructorParams);
//省略代码
//创建代理类
return cons.newInstance(new Object[]{h});
//省略代码
}
进入getProxyClass0方法
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
return proxyClassCache.get(loader, interfaces);
}
从这个proxyClassCache 来获得这个接口的代理类
public V get(K key, P parameter) {
//省略代码···
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
//第一次进来这里是空的,先执行后面的逻辑,然后再进到这里
if (supplier != null) {
//supplier是factory内部类
V value = supplier.get();
if (value != null) {
return value;
}
}
//创建一个内部类factory
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
//把这个内部类factory复制给supplier
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
进入java.lang.reflect.WeakCache.Factory
private final class Factory implements Supplier<V> {
private final K key;
private final P parameter;
private final Object subKey;
private final ConcurrentMap<Object, Supplier<V>> valuesMap;
Factory(K key, P parameter, Object subKey,
ConcurrentMap<Object, Supplier<V>> valuesMap) {
this.key = key;
this.parameter = parameter;
this.subKey = subKey;
this.valuesMap = valuesMap;
}
@Override
public synchronized V get() {
//省略代码
//这里的valueFactory是proxy的成员new WeakCache<>(new KeyFactory(), new ProxyClassFactory())中的ProxyClassFactory
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
//省略代码
}
}
进入java.lang.reflect.Proxy.ProxyClassFactory#apply
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
//省略代码
//生成代理类字节码
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
//省略代码
//加载字节码到jvm中
return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length);
//省略代码
}
因为设置了System.getProperties().put(“sun.misc.ProxyGenerator.saveGeneratedFiles”,“true”);
可以查看生成的代理类
public final class $Proxy0 extends Proxy implements TargetInterface {
//省略代码
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
//TargetInterface 的function方法
public final void function() throws {
try {
//这里会调用它的父类(proxy)的InvocationHandler的invoke方法,也就是自己实现的InvocationHandler类的方法
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
}
cglib动态代理
被代理的接口类
public interface TargetInterface {
void function();
}
被代理的类
public class Target implements TargetInterface{
@Override
public void function() {
System.out.println("方法执行");
}
}
测试
public class CglibProxyTest {
public static void main(String[] args) {
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "code");
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Target.class);
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("方法执行前增强,方法名:"+ method.getName());
System.out.println("methodProxy:"+ methodProxy.getSuperName());
Object object = methodProxy.invokeSuper(o, objects);
System.out.println("方法执行后-------------------");
return object;
}
});
Target target= (Target)enhancer.create();
target.function();
}
}
进入enhancer.create()方法
public Object create() {
classOnly = false;
argumentTypes = null;
return createHelper();
}
private Object createHelper() {
preValidate();
Object key = KEY_FACTORY.newInstance((superclass != null) ? superclass.getName() : null,
ReflectUtils.getNames(interfaces),
filter == ALL_ZERO ? null : new WeakCacheKey<CallbackFilter>(filter),
callbackTypes,
useFactory,
interceptDuringConstruction,
serialVersionUID);
this.currentKey = key;
Object result = super.create(key);
return result;
}
进入net.sf.cglib.core.AbstractClassGenerator#create
protected Object create(Object key) {
try {
ClassLoader loader = getClassLoader();
Map<ClassLoader, ClassLoaderData> cache = CACHE;
ClassLoaderData data = cache.get(loader);
if (data == null) {
synchronized (AbstractClassGenerator.class) {
cache = CACHE;
data = cache.get(loader);
if (data == null) {
Map<ClassLoader, ClassLoaderData> newCache = new WeakHashMap<ClassLoader, ClassLoaderData>(cache);
//在net.sf.cglib.core.AbstractClassGenerator.ClassLoaderData#ClassLoaderData-->net.sf.cglib.proxy.Enhancer#wrapCachedClass-->net.sf.cglib.proxy.Enhancer.EnhancerFactoryData#EnhancerFactoryData拿到构造器
data = new ClassLoaderData(loader);
newCache.put(loader, data);
CACHE = newCache;
}
}
}
this.key = key;
Object obj = data.get(this, getUseCache());
if (obj instanceof Class) {
return firstInstance((Class) obj);
}
//在net.sf.cglib.proxy.Enhancer#nextInstance-->net.sf.cglib.proxy.Enhancer.EnhancerFactoryData#newInstance-->net.sf.cglib.core.ReflectUtils#newInstance(java.lang.reflect.Constructor, java.lang.Object[])创建代理对象
return nextInstance(obj);
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new CodeGenerationException(e);
}
}
前面加了System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, “code”)在code文件下找到代理类
查看这个继承了target的代理类
public class Target$$EnhancerByCGLIB$$bda13b1b extends Target implements Factory {
//省略代码
public final void function() {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
if (var10000 != null) {
//调用自己写的MethodInterceptor的intercept方法,methodProxy会调用被代理的类被代理成的fastclass的function方法
var10000.intercept(this, CGLIB$function$0$Method, CGLIB$emptyArgs, CGLIB$function$0$Proxy);
} else {
super.function();
}
}
//省略代码
}