文章目錄
- 動態代理
- 例子代碼
- Proxy.newProxyInstance()
- getProxyClass0(loader, intfs)
- proxyClassCache.get(loader, interfaces)
- Factory:factory.get()
- Proxy:ProxyClassFactory:apply()
- 生成的代理類
- 代理類的helloworld()
- 總結
動態代理
用一個簡單的例子來描述動態代理,你想租房子,一般的話,你需要四處找房子,很辛苦,你想在家躺著交了錢就行,所以你找了個代理(中介),代理去找好了房子,和房東商量,你過來看下房子簽合同交錢就好了,這就是代理的作用,(找中介需謹慎,中介不同于代碼,代碼不會騙人)
實際代碼中,當你有一個已有的方法,你在不希望修改它的前提下想要擴展它的功能,即可使用動態代理,典型案例就是Spring AOP,
例子代碼
/**
* @author ddd
* @create 2021-06-25 19:21
* #desc 動態代理需要一個行為介面
**/
public interface action {
public void helloworld();
}
/**
* @author ddd
* @create 2021-06-25
* #desc 代理類
* **/
public class agent implements InvocationHandler {
private action action;
public agent(action action){
this.action=action;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(" 辛苦找房! " );
Object getmethod=method.invoke(action,args);
return getmethod;
}
}
/**
* @author ddd
* @create 2021-06-25
* @desc 顧客
**/
public class Custom implements action{
@Override
public void helloworld() {
System.out.println(" 看房,簽合同,交錢! ");
}
}
/**
* @author ddd
* @create 2021-06-25
* @desc 運行類
**/
public class Main {
public static void main(String[] args) {
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
action action=new Custom();
InvocationHandler handlerProxy=new agent(action);
/*
這一步會在記憶體中生成動態代理類
*/
action actionInstance = (My.DesignPattern.Agent.Jdk.action) Proxy.newProxyInstance(handlerProxy.getClass().getClassLoader(),
action.getClass().getInterfaces(),
handlerProxy);
actionInstance.helloworld();
}
}
Proxy.newProxyInstance()
大家都說動態代理很重要,用起來也很方便,被代理類實作一個行為介面,代理類實作InvocationHandler 介面,呼叫Proxy.newProxyInstance()即可生成一個代理類,那到底是怎么生成的代理類?我們進下原始碼Proxy.newProxyInstance()
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
/**
* 傳入的代理類非空
*/
Objects.requireNonNull(h);
// 使用克隆的方式拿到介面,新知識,什么是克隆?
final Class<?>[] intfs = interfaces.clone();
// 系統安全性檢查
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// check Proxy Access 看名字就可以了解,檢查是否可以代理
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
*
* 上面英文是原始碼注釋
* 查找或者生成一個代理
* 哎!有意思,查找,或者,生成,說明有兩種方式
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*
* 原始碼注釋:使用構造方法生成代理類
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
/**
* 使用構造方法生成代理類
*/
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
/**
* 回傳new的物件
*/
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
getProxyClass0(loader, intfs)
上面有一行代碼的注釋是查找或者生成一個代理類,我們來這個方法的原始碼
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
// 又封裝一層,接著進入proxyClassCache.get
return proxyClassCache.get(loader, interfaces);
}
proxyClassCache.get(loader, interfaces)
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
/**
* 從快取中查找,咦,這就是查找一個代理類,但是我們還沒有生成過
* 那在后續肯定有生成代理類放入快取的操作,
* 利用快取的話再次訪問的速度就會很快
*
* key是什么,handlerProxy.getClass().getClassLoader()
*/
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
ConcurrentMap<Object, Supplier<V>> oldValuesMap
= map.putIfAbsent(cacheKey,
valuesMap = new ConcurrentHashMap<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
/**
* Supplier生產者介面,函式型介面,有必要去了解一下
* 這里用于生產代理類
*/
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
/**
* 非空即可獲得代理類
* 第一次進入valuesMap是空的,map.get()獲取不到
* 所以回圈條件是while(ture)
* 后面會將一個Factory賦值給supplier,然后通過factory.get()來獲取
*/
V value = supplier.get();
if (value != null) {
return value;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a 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 = 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);
}
}
}
}
Factory:factory.get()
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() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
// something changed while we were waiting:
// might be that we were replaced by a CacheValue
// or were removed because of failure ->
// return null to signal WeakCache.get() to retry
// the loop
return null;
}
// else still us (supplier == this)
// create new value
V value = null;
try {
/**
* 關鍵代碼只在這一句,valueFactory.apply(key, parameter)非空即可
* 再去看valueFactory.apply(key, parameter)
*/
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;
// wrap value with CacheValue (WeakReference)
CacheValue<V> cacheValue = new CacheValue<>(value);
// put into reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
// try replacing us with CacheValue (this should always succeed)
if (!valuesMap.replace(subKey, this, cacheValue)) {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
Proxy:ProxyClassFactory:apply()
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
/**
* 獲取所有介面資訊并便利
*/
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
/**
* Class.forName作用是要求JVM查找并加載指定的類,相當于將介面實體化
* ClassLoader loader是我們一開始傳入的自己類的加載器
*/
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
/**
* 判斷當前類的實體化是否與我們創建的類是同一個加載器生成的
*/
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
// 代理類放在哪個路徑下
// 介面的權限
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
*/
for (Class<?> intf : interfaces) {
/**
* 獲取介面的權限
*/
int flags = intf.getModifiers();
/**
* 如果是public,則放在同一路徑下
*/
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
}
生成的代理類
以上程序就生成了代理類,那最終我們生成的代理類在哪呢?
在開頭的例子中,我們在Main類中加了這么一行代碼,它可以將我們生成的代理類保存到本地
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
運行之后就可以看到

代理類的helloworld()
我們來看代理類的helloworld方法
public final class $Proxy0 extends Proxy implements action{
---
/*
而我們一開始在最初的main方法中,
InvocationHandler handlerProxy=new agent(action);
action actionInstance = (My.DesignPattern.Agent.Jdk.action)Proxy.newProxyInstance(handlerProxy.getClass().getClassLoader(),
action.getClass().getInterfaces(),
handlerProxy);
又通過$Proxy0構造方法傳了new agent(action),是InvocationHandler 的實作類
所以Proxy 類中的InvocationHandl就是我們寫的代理類
*/
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final void helloworld() throws {
try {
/**
* 呼叫了父類的h變數的invoke,即agent類中的invoke
*/
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
---
}
總結
1、動態代理基于反射,可以在程式運行時得到一個類的全部資訊,
2、反射基于JVM的類加載機制和JVM記憶體模型中類,介面模板的存放,
3、動態代理通過以上技術在運行時動態生成一個代理物件,
4、為什么說是動態,因為agent傳入的引數是action介面,可以在運行時傳入任何實作了action介面的類來完成代理,使用更加靈活,
5、此文僅個人理解,并且因為反射涉及JVM知識,內容過多,未進一步深入,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/296865.html
標籤:java
上一篇:從 JVM 層面理解 i++ 和 ++i 的真正區別!
下一篇:SpringBoot2.5解決跨域問題2021年秋季新方法 SpringBoot+Vue前后端分離解決session不一致的問題
