1. 代理模式
代理模式是常用的設計模式之一,其特征是代理類與被代理類有相同的接口,代理類可以為被代理類方法執行進行前置後置處理,增強被代理類方法

代理模式的類結構通常如上圖所示,代理類與被代理類之間會存在關聯關系,一個代理類的對象持有一個被代理類的對象。代理類的對象本身并不真正實作服務,而是通過調用被代理類對象的相關方法來提供特定的服務
2. 動态代理使用
代理類并不是在 Java 代碼中定義,而是在運作時根據在 Java 代碼中的“訓示”動态生成(位元組碼由JVM在運作時動态生成而非預存在任何一個
.class
檔案中), 這種在程式運作時建立代理類的代理方式被稱為動态代理,它的優勢在于可以友善地對代理類的函數進行統一處理。
這是因為所有被代理執行的方法,都是通過
InvocationHandler#invoke()
方法調用,相當于給被代理類所有方法套了一層殼,是以隻要在這個方法中統一處理,就可以對所有被代理的方法進行相同的操作了
以下代碼展示了動态代理的簡單使用,其基本步驟如下:
- 定義一個公共接口,本例中為
,接口中有一個抽象方法IHello
- 定義一個實作了公共接口的實體類作為被代理類,本例中被代理類
實作了 Hello
接口,重寫了接口中的抽象方法IHello
- 定義一個實作了
接口的方法攔截類,重寫 InvocationHandler
方法實作攔截到被代理類方法執行時候的處理邏輯invoke()
- 通過
方法生成代理對象,持有代理對象之後執行接口方法即可Proxy.newProxyInstance()
public class ServiceProxy {
public interface IHello {
String sayHi();
}
public static class Hello implements IHello {
@Override
public String sayHi() {
return "Hello";
}
}
// 動态代理類
public static class ProxyHandler<T> implements InvocationHandler {
private T origin;
public ProxyHandler(T origin) {
this.origin = origin;
}
/**
* @param o 代理對象引用
* @param method 正在執行目标的方法
* @param objects 目标方法執行時的入參
*/
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
String s = "proxy";
s += method.invoke(origin, objects);
return s;
}
}
public static void main(String[] args) {
IHello IHello = (IHello) getInstance(IHello.class, new ProxyHandler<>(new Hello()));
System.out.println(IHello.toString());
generateProxyClass();
}
// 建立代理對象
public static <T> Object getInstance(Class<T> clazz, ProxyHandler<T> handler) {
return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, handler);
}
private static void generateProxyClass() {
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", Hello.class.getInterfaces());
String path = "/Users/nathan.yang/workspace/algorithm_Java/out/StuProxy.class";
try (FileOutputStream fos = new FileOutputStream(path)) {
fos.write(classFile);
fos.flush();
System.out.println("代理類檔案寫入成功");
} catch (Exception e) {
System.out.println("寫檔案錯誤");
}
}
}
3. 動态代理原理
1.
Proxy#newProxyInstance()
方法是動态代理的入口,其生成動态代理對象主要有以下幾個步驟:
-
方法生成代理類getProxyClass0()
- 擷取到代理類後将
對象入參,反射調用構造方法生成動态代理對象InvocationHandler
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) {
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;
}
});
}
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);
}
}
2.
Proxy#getProxyClass0()
方法其實是從一個
WeakCache
中去擷取代理類,其擷取邏輯是如果緩存類中沒有代理類的話就調用
ProxyClassFactory#apply()
,通過代理類工廠去即時生成一個代理類,其步驟如下:
- 首先通過指定的類加載器去驗證目标接口是否可被其加載
- 通過接口所在包等條件決定代理類所在包及代理類的全限定名稱,代理類名稱是
包名+$Proxy+id
- 通過
生成位元組碼數組,然後調用 ProxyGenerator.generateProxyClass()
方法 native
将其動态生成的代理類位元組碼加載到記憶體中defineClass0()
- 另外,公衆号Java精選,回複java面試,擷取面試題資料
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);
}
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 {
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();
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());
}
}
3.反射擷取到代理類參數為
InvocationHandler.class
的構造器,其實也就是
Proxy
的帶參構造器,調用構造器
cons.newInstance(new Object[]{h})
生成代理對象
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
private static void generateProxyClass() {
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", Hello.class.getInterfaces());
String path = "/Users/nathan/workspace/algorithm_Java/out/StuProxy.class";
try (FileOutputStream fos = new FileOutputStream(path)) {
fos.write(classFile);
fos.flush();
System.out.println("代理類檔案寫入成功");
} catch (Exception e) {
System.out.println("寫檔案錯誤");
}
}
- 通過
代碼塊将被代理類中每一個方法封裝為 static
對象,生成方法表Method
- 代理類對象執行被代理類同名方法時,通過其父類
保留的指向Proxy
對象的引用調用 InvocationHandler
方法,完成動态代理InvocationHandler#invoke()
public final class $Proxy0 extends Proxy implements IHello {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final String sayHi() throws {
try {
// 父類 Proxy 保留的指向 InvocationHandler 對象的引用調用 invoke() 方法
return (String)super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
......
// 方法表,公衆号Java精選
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("ServiceProxy$IHello").getMethod("sayHi");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}