java動態代理
代理模式
為其他物件提供一個代理以控制對某個物件的訪問。代理類主要負責為委託了(真實物件)預處理訊息、過濾訊息、傳遞訊息給委託類,代理類不現實具體服務,而是利用委託類來完成服務,並將執行結果封裝處理。
其實就是代理類為被代理類預處理訊息、過濾訊息並在此之後將訊息轉發給被代理類,之後還能進行訊息的後置處理。代理類和被代理類通常會存在關聯關係(即上面提到的持有的被帶離物件的引用),代理類本身不實現服務,而是通過呼叫被代理類中的方法來提供服務。
靜態代理
建立一個介面,然後建立被代理的類實現該介面並且實現該介面中的抽象方法。之後再建立一個代理類,同時使其也實現這個介面。在代理類中持有一個被代理物件的引用,而後在代理類方法中呼叫該物件的方法。
以下是靜態代理的例子:
介面:
public interface HelloInterface {
void sayHello();
}
被代理類:
public class Hello implements HelloInterface{
@Override
public void sayHello() {
System.out.println("Hello zhanghao!");
}
}
代理類:
public class HelloProxy implements HelloInterface{ private HelloInterface helloInterface = new Hello(); @Override public void sayHello() { System.out.println("Before invoke sayHello" ); helloInterface.sayHello(); System.out.println("After invoke sayHello"); } }
代理類呼叫:
public static void main(String[] args) {
HelloProxy helloProxy = new HelloProxy();
helloProxy.sayHello();
}
輸出:
Before invoke sayHello
Hello zhanghao!
After invoke sayHello
使用靜態代理很容易就完成了對一個類的代理操作。但是靜態代理的缺點也暴露了出來:由於代理只能為一個類服務,如果需要代理的類很多,那麼就需要編寫大量的代理類,比較繁瑣。
動態代理
利用反射機制在執行時建立代理類。
介面、被代理類不變,我們構建一個handler類來實現InvocationHandler介面。
public class ProxyHandler implements InvocationHandler{
private Object object;
public ProxyHandler(Object object){
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before invoke " + method.getName());
method.invoke(object, args);
System.out.println("After invoke " + method.getName());
return null;
}
}
執行動態代理:
public static void main(String[] args) {
System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
HelloInterface hello = new Hello();
InvocationHandler handler = new ProxyHandler(hello);
HelloInterface proxyHello = (HelloInterface) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);
proxyHello.sayHello();
}
輸出:
Before invoke sayHello
Hello zhanghao!
After invoke sayHello
通過Proxy類的靜態方法newProxyInstance返回一個介面的代理例項。針對不同的代理類,傳入相應的代理程式控制器InvocationHandler。
如果新來一個被代理類Bye,如:
public interface ByeInterface {
void sayBye();
}
public class Bye implements ByeInterface {
@Override
public void sayBye() {
System.out.println("Bye zhanghao!");
}
}
執行過程:
public static void main(String[] args) {
System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
HelloInterface hello = new Hello();
ByeInterface bye = new Bye();
InvocationHandler handler = new ProxyHandler(hello);
InvocationHandler handler1 = new ProxyHandler(bye);
HelloInterface proxyHello = (HelloInterface) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);
ByeInterface proxyBye = (ByeInterface) Proxy.newProxyInstance(bye.getClass().getClassLoader(), bye.getClass().getInterfaces(), handler1);
proxyHello.sayHello();
proxyBye.sayBye();
}
輸出:
Before invoke sayHello
Hello zhanghao!
After invoke sayHello
Before invoke sayBye
Bye zhanghao!
After invoke sayBye
動態代理底層實現
動態代理具體步驟:
- 通過實現 InvocationHandler 介面建立自己的呼叫處理器;
- 通過為 Proxy 類指定 ClassLoader 物件和一組 interface 來建立動態代理類;
- 通過反射機制獲得動態代理類的建構函式,其唯一引數型別是呼叫處理器介面型別;
- 通過建構函式建立動態代理類例項,構造時呼叫處理器物件作為引數被傳入。
既然生成代理物件是用的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) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
//生成代理類物件
Class<?> cl = getProxyClass0(loader, intfs);
//使用指定的呼叫處理程式獲取代理類的建構函式物件
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
//如果Class作用域為私有,通過 setAccessible 支援訪問
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
//獲取Proxy Class建構函式,建立Proxy代理例項。
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)生成代理類Proxy的Class物件。
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
//如果介面數量大於65535,丟擲非法引數錯誤
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
//如果指定介面的代理類已經存在與快取中,則不用新建立,直接從快取中取即可;
//如果快取中沒有指定代理物件,則通過ProxyClassFactory來建立一個代理物件。
return proxyClassCache.get(loader, interfaces);
}
ProxyClassFactory內部類建立、定義代理類,返回給定ClassLoader 和interfaces的代理類。
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>{
// 代理類的名字的字首統一為“$Proxy”
private static final String proxyClassNamePrefix = "$Proxy";
// 每個代理類字首後面都會跟著一個唯一的編號,如$Proxy0、$Proxy1、$Proxy2
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) {
//驗證類載入器載入介面得到物件是否與由apply函式引數傳入的物件相同
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");
}
//驗證這個Class物件是不是介面
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
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;
/*
*
* 生成指定代理類的位元組碼檔案
*/
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());
}
}
}
一系列檢查後,呼叫ProxyGenerator.generateProxyClass來生成位元組碼檔案。
public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
// 真正用來生成代理類位元組碼檔案的方法在這裡
final byte[] var4 = var3.generateClassFile();
// 儲存代理類的位元組碼檔案
if(saveGeneratedFiles) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
int var1 = var0.lastIndexOf(46);
Path var2;
if(var1 > 0) {
Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar), new String[0]);
Files.createDirectories(var3, new FileAttribute[0]);
var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
} else {
var2 = Paths.get(var0 + ".class", new String[0]);
}
Files.write(var2, var4, new OpenOption[0]);
return null;
} catch (IOException var4x) {
throw new InternalError("I/O exception saving generated file: " + var4x);
}
}
});
}
return var4;
}
生成代理類位元組碼檔案的generateClassFile方法:
private byte[] generateClassFile() {
//下面一系列的addProxyMethod方法是將介面中的方法和Object中的方法新增到代理方法中(proxyMethod)
this.addProxyMethod(hashCodeMethod, Object.class);
this.addProxyMethod(equalsMethod, Object.class);
this.addProxyMethod(toStringMethod, Object.class);
Class[] var1 = this.interfaces;
int var2 = var1.length;
int var3;
Class var4;
//獲得介面中所有方法並新增到代理方法中
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
Method[] var5 = var4.getMethods();
int var6 = var5.length;
for(int var7 = 0; var7 < var6; ++var7) {
Method var8 = var5[var7];
this.addProxyMethod(var8, var4);
}
}
Iterator var11 = this.proxyMethods.values().iterator();
List var12;
while(var11.hasNext()) {
var12 = (List)var11.next();
checkReturnTypes(var12);
}
Iterator var15;
try {
//生成代理類的建構函式
this.methods.add(this.generateConstructor());
var11 = this.proxyMethods.values().iterator();
while(var11.hasNext()) {
var12 = (List)var11.next();
var15 = var12.iterator();
while(var15.hasNext()) {
ProxyGenerator.ProxyMethod var16 = (ProxyGenerator.ProxyMethod)var15.next();
this.fields.add(new ProxyGenerator.FieldInfo(var16.methodFieldName, "Ljava/lang/reflect/Method;", 10));
this.methods.add(var16.generateMethod());
}
}
this.methods.add(this.generateStaticInitializer());
} catch (IOException var10) {
throw new InternalError("unexpected I/O Exception", var10);
}
if(this.methods.size() > '\uffff') {
throw new IllegalArgumentException("method limit exceeded");
} else if(this.fields.size() > '\uffff') {
throw new IllegalArgumentException("field limit exceeded");
} else {
this.cp.getClass(dotToSlash(this.className));
this.cp.getClass("java/lang/reflect/Proxy");
var1 = this.interfaces;
var2 = var1.length;
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
this.cp.getClass(dotToSlash(var4.getName()));
}
this.cp.setReadOnly();
ByteArrayOutputStream var13 = new ByteArrayOutputStream();
DataOutputStream var14 = new DataOutputStream(var13);
try {
var14.writeInt(-889275714);
var14.writeShort(0);
var14.writeShort(49);
this.cp.write(var14);
var14.writeShort(this.accessFlags);
var14.writeShort(this.cp.getClass(dotToSlash(this.className)));
var14.writeShort(this.cp.getClass("java/lang/reflect/Proxy"));
var14.writeShort(this.interfaces.length);
Class[] var17 = this.interfaces;
int var18 = var17.length;
for(int var19 = 0; var19 < var18; ++var19) {
Class var22 = var17[var19];
var14.writeShort(this.cp.getClass(dotToSlash(var22.getName())));
}
var14.writeShort(this.fields.size());
var15 = this.fields.iterator();
while(var15.hasNext()) {
ProxyGenerator.FieldInfo var20 = (ProxyGenerator.FieldInfo)var15.next();
var20.write(var14);
}
var14.writeShort(this.methods.size());
var15 = this.methods.iterator();
while(var15.hasNext()) {
ProxyGenerator.MethodInfo var21 = (ProxyGenerator.MethodInfo)var15.next();
var21.write(var14);
}
var14.writeShort(0);
return var13.toByteArray();
} catch (IOException var9) {
throw new InternalError("unexpected I/O Exception", var9);
}
}
}
位元組碼生成後,呼叫defineClass0來解析位元組碼,生成了Proxy的Class物件。在瞭解完代理類動態生成過程後,生產的代理類是怎樣的,誰來執行這個代理類。