Java編譯器編譯好Java文件之後,產生.class 文件在磁盤中。這種class文件是二進制文件,內容是隻有JVM虛擬機能夠識別的機器碼。JVM虛擬機讀取字節碼文件,取出二進制數據,加載到內存中,解析.class 文件內的信息,生成對應的 Class對象:
class字節碼文件是根據JVM虛擬機規範中規定的字節碼組織規則生成的、具體class文件是怎樣組織類信息的,可以參考 此博文:深入理解Java Class文件格式系列。或者是Java虛擬機規範。
下面通過一段代碼演示手動加載 class文件字節碼到系統內,轉換成class對象,然後再實例化的過程:
a. 定義一個 Programmer類:
- package samples;
- /**
- * 程序猿類
- * @author louluan
- */
- public class Programmer {
- public void code()
- {
- System.out.println("I'm a Programmer,Just Coding.....");
- }
- }
package samples;
/**
* 程序猿類
* @author louluan
*/
public class Programmer {
public void code()
{
System.out.println("I'm a Programmer,Just Coding.....");
}
}
b. 自定義一個類加載器:
- package samples;
- /**
- * 自定義一個類加載器,用於將字節碼轉換爲class對象
- * @author louluan
- */
- public class MyClassLoader extends ClassLoader {
- public Class<?> defineMyClass( byte[] b, int off, int len)
- {
- return super.defineClass(b, off, len);
- }
- }
package samples;
/**
* 自定義一個類加載器,用於將字節碼轉換爲class對象
* @author louluan
*/
public class MyClassLoader extends ClassLoader {
public Class<?> defineMyClass( byte[] b, int off, int len)
{
return super.defineClass(b, off, len);
}
}
c. 然後編譯成Programmer.class文件,在程序中讀取字節碼,然後轉換成相應的class對象,再實例化:
- package samples;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.URL;
- public class MyTest {
- public static void main(String[] args) throws IOException {
- //讀取本地的class文件內的字節碼,轉換成字節碼數組
- File file = new File(".");
- InputStream input = new FileInputStream(file.getCanonicalPath()+"\bin\samples\Programmer.class");
- byte[] result = new byte[1024];
- int count = input.read(result);
- // 使用自定義的類加載器將 byte字節碼數組轉換爲對應的class對象
- MyClassLoader loader = new MyClassLoader();
- Class clazz = loader.defineMyClass( result, 0, count);
- //測試加載是否成功,打印class 對象的名稱
- System.out.println(clazz.getCanonicalName());
- //實例化一個Programmer對象
- Object o= clazz.newInstance();
- try {
- //調用Programmer的code方法
- clazz.getMethod("code", null).invoke(o, null);
- } catch (IllegalArgumentException | InvocationTargetException
- | NoSuchMethodException | SecurityException e) {
- e.printStackTrace();
- }
- }
- }
package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class MyTest {
public static void main(String[] args) throws IOException {
//讀取本地的class文件內的字節碼,轉換成字節碼數組
File file = new File(".");
InputStream input = new FileInputStream(file.getCanonicalPath()+"\bin\samples\Programmer.class");
byte[] result = new byte[1024];
int count = input.read(result);
// 使用自定義的類加載器將 byte字節碼數組轉換爲對應的class對象
MyClassLoader loader = new MyClassLoader();
Class clazz = loader.defineMyClass( result, 0, count);
//測試加載是否成功,打印class 對象的名稱
System.out.println(clazz.getCanonicalName());
//實例化一個Programmer對象
Object o= clazz.newInstance();
try {
//調用Programmer的code方法
clazz.getMethod("code", null).invoke(o, null);
} catch (IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
}
}
以上代碼演示了,通過字節碼加載成class 對象的能力,下面看一下在代碼中如何生成class文件的字節碼。
在運行期的代碼中生成二進制字節碼
由於JVM通過字節碼的二進制信息加載類的,那麼,如果我們在運行期系統中,遵循Java編譯系統組織.class文件的格式和結構,生成相應的二進制數據,然後再把這個二進制數據加載轉換成對應的類,這樣,就完成了在代碼中,動態創建一個類的能力了。
在運行時期可以按照Java虛擬機規範對class文件的組織規則生成對應的二進制字節碼。當前有很多開源框架可以完成這些功能,如ASM,Javassist。
Java字節碼生成開源框架介紹--ASM:
ASM 是一個 Java 字節碼操控框架。它能夠以二進制形式修改已有類或者動態生成類。ASM 可以直接產生二進制 class 文件,也可以在類被加載入 Java 虛擬機之前動態改變類行爲。ASM 從類文件中讀入信息後,能夠改變類行爲,分析類信息,甚至能夠根據用戶要求生成新類。
不過ASM在創建class字節碼的過程中,操縱的級別是底層JVM的彙編指令級別,這要求ASM使用者要對class組織結構和JVM彙編指令有一定的瞭解。
下面通過ASM 生成下面類Programmer的class字節碼:
- package com.samples;
- import java.io.PrintStream;
- public class Programmer {
- public void code()
- {
- System.out.println("I'm a Programmer,Just Coding.....");
- }
- }
package com.samples;
import java.io.PrintStream;
public class Programmer {
public void code()
{
System.out.println("I'm a Programmer,Just Coding.....");
}
}
使用ASM框架提供了ClassWriter 接口,通過訪問者模式進行動態創建class字節碼,看下面的例子:
- package samples;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import org.objectweb.asm.ClassWriter;
- import org.objectweb.asm.MethodVisitor;
- import org.objectweb.asm.Opcodes;
- public class MyGenerator {
- public static void main(String[] args) throws IOException {
- System.out.println();
- ClassWriter classWriter = new ClassWriter(0);
- // 通過visit方法確定類的頭部信息
- classWriter.visit(Opcodes.V1_7,// java版本
- Opcodes.ACC_PUBLIC,// 類修飾符
- "Programmer", // 類的全限定名
- null, "java/lang/Object", null);
- //創建構造函數
- MethodVisitor mv = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
- mv.visitCode();
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>","()V");
- mv.visitInsn(Opcodes.RETURN);
- mv.visitMaxs(1, 1);
- mv.visitEnd();
- // 定義code方法
- MethodVisitor methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "code", "()V",
- null, null);
- methodVisitor.visitCode();
- methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out",
- "Ljava/io/PrintStream;");
- methodVisitor.visitLdcInsn("I'm a Programmer,Just Coding.....");
- methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println",
- "(Ljava/lang/String;)V");
- methodVisitor.visitInsn(Opcodes.RETURN);
- methodVisitor.visitMaxs(2, 2);
- methodVisitor.visitEnd();
- classWriter.visitEnd();
- // 使classWriter類已經完成
- // 將classWriter轉換成字節數組寫到文件裏面去
- byte[] data = classWriter.toByteArray();
- File file = new File("D://Programmer.class");
- FileOutputStream fout = new FileOutputStream(file);
- fout.write(data);
- fout.close();
- }
- }
package samples;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
public class MyGenerator {
public static void main(String[] args) throws IOException {
System.out.println();
ClassWriter classWriter = new ClassWriter(0);
// 通過visit方法確定類的頭部信息
classWriter.visit(Opcodes.V1_7,// java版本
Opcodes.ACC_PUBLIC,// 類修飾符
"Programmer", // 類的全限定名
null, "java/lang/Object", null);
//創建構造函數
MethodVisitor mv = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>","()V");
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// 定義code方法
MethodVisitor methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "code", "()V",
null, null);
methodVisitor.visitCode();
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out",
"Ljava/io/PrintStream;");
methodVisitor.visitLdcInsn("I'm a Programmer,Just Coding.....");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println",
"(Ljava/lang/String;)V");
methodVisitor.visitInsn(Opcodes.RETURN);
methodVisitor.visitMaxs(2, 2);
methodVisitor.visitEnd();
classWriter.visitEnd();
// 使classWriter類已經完成
// 將classWriter轉換成字節數組寫到文件裏面去
byte[] data = classWriter.toByteArray();
File file = new File("D://Programmer.class");
FileOutputStream fout = new FileOutputStream(file);
fout.write(data);
fout.close();
}
}
上述的代碼執行過後,用Java反編譯工具(如JD_GUI)打開D盤下生成的Programmer.class,可以看到以下信息:
再用上面我們定義的類加載器將這個class文件加載到內存中,然後 創建class對象,並且實例化一個對象,調用code方法,會看到下面的結果:
以上表明:在代碼裏生成字節碼,並動態地加載成class對象、創建實例是完全可以實現的。
Java字節碼生成開源框架介紹--Javassist:
Javassist是一個開源的分析、編輯和創建Java字節碼的類庫。是由東京工業大學的數學和計算機科學系的 Shigeru Chiba (千葉 滋)所創建的。它已加入了開放源代碼JBoss 應用服務器項目,通過使用Javassist對字節碼操作爲JBoss實現動態AOP框架。javassist是jboss的一個子項目,其主要的優點,在於簡單,而且快速。直接使用java編碼的形式,而不需要了解虛擬機指令,就能動態改變類的結構,或者動態生成類。
下面通過Javassist創建上述的Programmer類:
- import javassist.ClassPool;
- import javassist.CtClass;
- import javassist.CtMethod;
- import javassist.CtNewMethod;
- public class MyGenerator {
- public static void main(String[] args) throws Exception {
- ClassPool pool = ClassPool.getDefault();
- //創建Programmer類
- CtClass cc= pool.makeClass("com.samples.Programmer");
- //定義code方法
- CtMethod method = CtNewMethod.make("public void code(){}", cc);
- //插入方法代碼
- method.insertBefore("System.out.println("I'm a Programmer,Just Coding.....");");
- cc.addMethod(method);
- //保存生成的字節碼
- cc.writeFile("d://temp");
- }
- }
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
public class MyGenerator {
public static void main(String[] args) throws Exception {
ClassPool pool = ClassPool.getDefault();
//創建Programmer類
CtClass cc= pool.makeClass("com.samples.Programmer");
//定義code方法
CtMethod method = CtNewMethod.make("public void code(){}", cc);
//插入方法代碼
method.insertBefore("System.out.println("I'm a Programmer,Just Coding.....");");
cc.addMethod(method);
//保存生成的字節碼
cc.writeFile("d://temp");
}
}
通過JD-gui反編譯工具打開Programmer.class 可以看到以下代碼:
代理的基本構成:
代理模式上,基本上有Subject角色,RealSubject角色,Proxy角色。其中:Subject角色負責定義RealSubject和Proxy角色應該實現的接口;RealSubject角色用來真正完成業務服務功能;Proxy角色負責將自身的Request請求,調用realsubject 對應的request功能來實現業務功能,自己不真正做業務。
上面的這幅代理結構圖是典型的靜態的代理模式:
當在代碼階段規定這種代理關係,Proxy類通過編譯器編譯成class文件,當系統運行時,此class已經存在了。這種靜態的代理模式固然在訪問無法訪問的資源,增強現有的接口業務功能方面有很大的優點,但是大量使用這種靜態代理,會使我們系統內的類的規模增大,並且不易維護;並且由於Proxy和RealSubject的功能 本質上是相同的,Proxy只是起到了中介的作用,這種代理在系統中的存在,導致系統結構比較臃腫和鬆散。
爲了解決這個問題,就有了動態地創建Proxy的想法:在運行狀態中,需要代理的地方,根據Subject 和RealSubject,動態地創建一個Proxy,用完之後,就會銷燬,這樣就可以避免了Proxy 角色的class在系統中冗雜的問題了。
下面以一個代理模式實例闡述這一問題:
將車站的售票服務抽象出一個接口TicketService,包含問詢,賣票,退票功能,車站類Station實現了TicketService接口,車票代售點StationProxy則實現了代理角色的功能,類圖如下所示。
對應的靜態的代理模式代碼如下所示:
- package com.foo.proxy;
- /**
- * 售票服務接口實現類,車站
- * @author louluan
- */
- public class Station implements TicketService {
- @Override
- public void sellTicket() {
- System.out.println("
- 售票.....
- ");
- }
- @Override
- public void inquire() {
- System.out.println("
- 問詢。。。。
- ");
- }
- @Override
- public void withdraw() {
- System.out.println("
- 退票......
- ");
- }
- }
package com.foo.proxy;
/**
* 售票服務接口實現類,車站
* @author louluan
*/
public class Station implements TicketService {
@Override
public void sellTicket() {
System.out.println("
售票.....
");
}
@Override
public void inquire() {
System.out.println("
問詢。。。。
");
}
@Override
public void withdraw() {
System.out.println("
退票......
");
}
}
- package com.foo.proxy;
- /**
- * 售票服務接口
- * @author louluan
- */
- public interface TicketService {
- //售票
- public void sellTicket();
- //問詢
- public void inquire();
- //退票
- public void withdraw();
- }
package com.foo.proxy;
/**
* 售票服務接口
* @author louluan
*/
public interface TicketService {
//售票
public void sellTicket();
//問詢
public void inquire();
//退票
public void withdraw();
}
- package com.foo.proxy;
- /**
- * 車票代售點
- * @author louluan
- *
- */
- public class StationProxy implements TicketService {
- private Station station;
- public StationProxy(Station station){
- this.station = station;
- }
- @Override
- public void sellTicket() {
- // 1.做真正業務前,提示信息
- this.showAlertInfo("××××您正在使用車票代售點進行購票,每張票將會收取5元手續費!××××");
- // 2.調用真實業務邏輯
- station.sellTicket();
- // 3.後處理
- this.takeHandlingFee();
- this.showAlertInfo("××××歡迎您的光臨,再見!××××
- ");
- }
- @Override
- public void inquire() {
- // 1做真正業務前,提示信息
- this.showAlertInfo("××××歡迎光臨本代售點,問詢服務不會收取任何費用,本問詢信息僅供參考,具體信息以車站真實數據爲準!××××");
- // 2.調用真實邏輯
- station.inquire();
- // 3。後處理
- this.showAlertInfo("××××歡迎您的光臨,再見!××××
- ");
- }
- @Override
- public void withdraw() {
- // 1。真正業務前處理
- this.showAlertInfo("××××歡迎光臨本代售點,退票除了扣除票額的20%外,本代理處額外加收2元手續費!××××");
- // 2.調用真正業務邏輯
- station.withdraw();
- // 3.後處理
- this.takeHandlingFee();
- }
- /*
- * 展示額外信息
- */
- private void showAlertInfo(String info) {
- System.out.println(info);
- }
- /*
- * 收取手續費
- */
- private void takeHandlingFee() {
- System.out.println("收取手續費,打印發票。。。。。
- ");
- }
- }
package com.foo.proxy;
/**
* 車票代售點
* @author louluan
*
*/
public class StationProxy implements TicketService {
private Station station;
public StationProxy(Station station){
this.station = station;
}
@Override
public void sellTicket() {
// 1.做真正業務前,提示信息
this.showAlertInfo("××××您正在使用車票代售點進行購票,每張票將會收取5元手續費!××××");
// 2.調用真實業務邏輯
station.sellTicket();
// 3.後處理
this.takeHandlingFee();
this.showAlertInfo("××××歡迎您的光臨,再見!××××
");
}
@Override
public void inquire() {
// 1做真正業務前,提示信息
this.showAlertInfo("××××歡迎光臨本代售點,問詢服務不會收取任何費用,本問詢信息僅供參考,具體信息以車站真實數據爲準!××××");
// 2.調用真實邏輯
station.inquire();
// 3。後處理
this.showAlertInfo("××××歡迎您的光臨,再見!××××
");
}
@Override
public void withdraw() {
// 1。真正業務前處理
this.showAlertInfo("××××歡迎光臨本代售點,退票除了扣除票額的20%外,本代理處額外加收2元手續費!××××");
// 2.調用真正業務邏輯
station.withdraw();
// 3.後處理
this.takeHandlingFee();
}
/*
* 展示額外信息
*/
private void showAlertInfo(String info) {
System.out.println(info);
}
/*
* 收取手續費
*/
private void takeHandlingFee() {
System.out.println("收取手續費,打印發票。。。。。
");
}
}
由於我們現在不希望靜態地有StationProxy類存在,希望在代碼中,動態生成器二進制代碼,加載進來。爲此,使用Javassist開源框架,在代碼中動態地生成StationProxy的字節碼:
- package com.foo.proxy;
- import java.lang.reflect.Constructor;
- import javassist.*;
- public class Test {
- public static void main(String[] args) throws Exception {
- createProxy();
- }
- /*
- * 手動創建字節碼
- */
- private static void createProxy() throws Exception
- {
- ClassPool pool = ClassPool.getDefault();
- CtClass cc = pool.makeClass("com.foo.proxy.StationProxy");
- //設置接口
- CtClass interface1 = pool.get("com.foo.proxy.TicketService");
- cc.setInterfaces(new CtClass[]{interface1});
- //設置Field
- CtField field = CtField.make("private com.foo.proxy.Station station;", cc);
- cc.addField(field);
- CtClass stationClass = pool.get("com.foo.proxy.Station");
- CtClass[] arrays = new CtClass[]{stationClass};
- CtConstructor ctc = CtNewConstructor.make(arrays,null,CtNewConstructor.PASS_NONE,null,null, cc);
- //設置構造函數內部信息
- ctc.setBody("{this.station=$1;}");
- cc.addConstructor(ctc);
- //創建收取手續 takeHandlingFee方法
- CtMethod takeHandlingFee = CtMethod.make("private void takeHandlingFee() {}", cc);
- takeHandlingFee.setBody("System.out.println("收取手續費,打印發票。。。。。");");
- cc.addMethod(takeHandlingFee);
- //創建showAlertInfo 方法
- CtMethod showInfo = CtMethod.make("private void showAlertInfo(String info) {}", cc);
- showInfo.setBody("System.out.println($1);");
- cc.addMethod(showInfo);
- //sellTicket
- CtMethod sellTicket = CtMethod.make("public void sellTicket(){}", cc);
- sellTicket.setBody("{this.showAlertInfo("××××您正在使用車票代售點進行購票,每張票將會收取5元手續費!××××");"
- + "station.sellTicket();"
- + "this.takeHandlingFee();"
- + "this.showAlertInfo("××××歡迎您的光臨,再見!××××");}");
- cc.addMethod(sellTicket);
- //添加inquire方法
- CtMethod inquire = CtMethod.make("public void inquire() {}", cc);
- inquire.setBody("{this.showAlertInfo("××××歡迎光臨本代售點,問詢服務不會收取任何費用,本問詢信息僅供參考,具體信息以車站真實數據爲準!××××");"
- + "station.inquire();"
- + "this.showAlertInfo("××××歡迎您的光臨,再見!××××");}"
- );
- cc.addMethod(inquire);
- //添加widthraw方法
- CtMethod withdraw = CtMethod.make("public void withdraw() {}", cc);
- withdraw.setBody("{this.showAlertInfo("××××歡迎光臨本代售點,退票除了扣除票額的20%外,本代理處額外加收2元手續費!××××");"
- + "station.withdraw();"
- + "this.takeHandlingFee();}"
- );
- cc.addMethod(withdraw);
- //獲取動態生成的class
- Class c = cc.toClass();
- //獲取構造器
- Constructor constructor= c.getConstructor(Station.class);
- //通過構造器實例化
- TicketService o = (TicketService)constructor.newInstance(new Station());
- o.inquire();
- cc.writeFile("D://test");
- }
- }
package com.foo.proxy;
import java.lang.reflect.Constructor;
import javassist.*;
public class Test {
public static void main(String[] args) throws Exception {
createProxy();
}
/*
* 手動創建字節碼
*/
private static void createProxy() throws Exception
{
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.makeClass("com.foo.proxy.StationProxy");
//設置接口
CtClass interface1 = pool.get("com.foo.proxy.TicketService");
cc.setInterfaces(new CtClass[]{interface1});
//設置Field
CtField field = CtField.make("private com.foo.proxy.Station station;", cc);
cc.addField(field);
CtClass stationClass = pool.get("com.foo.proxy.Station");
CtClass[] arrays = new CtClass[]{stationClass};
CtConstructor ctc = CtNewConstructor.make(arrays,null,CtNewConstructor.PASS_NONE,null,null, cc);
//設置構造函數內部信息
ctc.setBody("{this.station=$1;}");
cc.addConstructor(ctc);
//創建收取手續 takeHandlingFee方法
CtMethod takeHandlingFee = CtMethod.make("private void takeHandlingFee() {}", cc);
takeHandlingFee.setBody("System.out.println("收取手續費,打印發票。。。。。");");
cc.addMethod(takeHandlingFee);
//創建showAlertInfo 方法
CtMethod showInfo = CtMethod.make("private void showAlertInfo(String info) {}", cc);
showInfo.setBody("System.out.println($1);");
cc.addMethod(showInfo);
//sellTicket
CtMethod sellTicket = CtMethod.make("public void sellTicket(){}", cc);
sellTicket.setBody("{this.showAlertInfo("××××您正在使用車票代售點進行購票,每張票將會收取5元手續費!××××");"
+ "station.sellTicket();"
+ "this.takeHandlingFee();"
+ "this.showAlertInfo("××××歡迎您的光臨,再見!××××");}");
cc.addMethod(sellTicket);
//添加inquire方法
CtMethod inquire = CtMethod.make("public void inquire() {}", cc);
inquire.setBody("{this.showAlertInfo("××××歡迎光臨本代售點,問詢服務不會收取任何費用,本問詢信息僅供參考,具體信息以車站真實數據爲準!××××");"
+ "station.inquire();"
+ "this.showAlertInfo("××××歡迎您的光臨,再見!××××");}"
);
cc.addMethod(inquire);
//添加widthraw方法
CtMethod withdraw = CtMethod.make("public void withdraw() {}", cc);
withdraw.setBody("{this.showAlertInfo("××××歡迎光臨本代售點,退票除了扣除票額的20%外,本代理處額外加收2元手續費!××××");"
+ "station.withdraw();"
+ "this.takeHandlingFee();}"
);
cc.addMethod(withdraw);
//獲取動態生成的class
Class c = cc.toClass();
//獲取構造器
Constructor constructor= c.getConstructor(Station.class);
//通過構造器實例化
TicketService o = (TicketService)constructor.newInstance(new Station());
o.inquire();
cc.writeFile("D://test");
}
}
上述代碼執行過後,會產生StationProxy的字節碼,並且用生成字節碼加載如內存創建對象,調用inquire()方法,會得到以下結果:
通過上面動態生成的代碼,我們發現,其實現相當地麻煩在創造的過程中,含有太多的業務代碼。我們使用上述創建Proxy代理類的方式的初衷是減少系統代碼的冗雜度,但是上述做法卻增加了在動態創建代理類過程中的複雜度:手動地創建了太多的業務代碼,並且封裝性也不夠,完全不具有可拓展性和通用性。如果某個代理類的一些業務邏輯非常複雜,上述的動態創建代理的方式是非常不可取的!
InvocationHandler角色的由來
仔細思考代理模式中的代理Proxy角色。Proxy角色在執行代理業務的時候,無非是在調用真正業務之前或者之後做一些“額外”業務。
有上圖可以看出,代理類處理的邏輯很簡單:在調用某個方法前及方法後做一些額外的業務。換一種思路就是:在觸發(invoke)真實角色的方法之前或者之後做一些額外的業務。那麼,爲了構造出具有通用性和簡單性的代理類,可以將所有的觸發真實角色動作交給一個觸發的管理器,讓這個管理器統一地管理觸發。這種管理器就是Invocation Handler。
動態代理模式的結構跟上面的靜態代理模式稍微有所不同,多引入了一個InvocationHandler角色。
先解釋一下InvocationHandler的作用:
在靜態代理中,代理Proxy中的方法,都指定了調用了特定的realSubject中的對應的方法:
在上面的靜態代理模式下,Proxy所做的事情,無非是調用在不同的request時,調用觸發realSubject對應的方法;更抽象點看,Proxy所作的事情;在Java中 方法(Method)也是作爲一個對象來看待了,
動態代理工作的基本模式就是將自己的方法功能的實現交給 InvocationHandler角色,外界對Proxy角色中的每一個方法的調用,Proxy角色都會交給InvocationHandler來處理,而InvocationHandler則調用具體對象角色的方法。如下圖所示:
在這種模式之中:代理Proxy 和RealSubject 應該實現相同的功能,這一點相當重要。(我這裏說的功能,可以理解爲某個類的public方法)
在面向對象的編程之中,如果我們想要約定Proxy 和RealSubject可以實現相同的功能,有兩種方式:
a.一個比較直觀的方式,就是定義一個功能接口,然後讓Proxy 和RealSubject來實現這個接口。
b.還有比較隱晦的方式,就是通過繼承。因爲如果Proxy 繼承自RealSubject,這樣Proxy則擁有了RealSubject的功能,Proxy還可以通過重寫RealSubject中的方法,來實現多態。
其中JDK中提供的創建動態代理的機制,是以a 這種思路設計的,而cglib 則是以b思路設計的。
JDK的動態代理創建機制----通過接口
比如現在想爲RealSubject這個類創建一個動態代理對象,JDK主要會做以下工作:
1. 獲取 RealSubject上的所有接口列表;
2. 確定要生成的代理類的類名,默認爲:com.sun.proxy.$ProxyXXXX ;
3. 根據需要實現的接口信息,在代碼中動態創建 該Proxy類的字節碼;
4 . 將對應的字節碼轉換爲對應的class 對象;
5. 創建InvocationHandler 實例handler,用來處理Proxy所有方法調用;
6. Proxy 的class對象 以創建的handler對象爲參數,實例化一個proxy對象
JDK通過 java.lang.reflect.Proxy包來支持動態代理,一般情況下,我們使用下面的newProxyInstance方法
static Object | newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h) 返回一個指定接口的代理類實例,該接口可以將方法調用指派到指定的調用處理程序。 |
在調用代理對象中的每一個方法時,在代碼內部,都是直接調用了InvocationHandler 的invoke方法,而invoke方法根據代理類傳遞給自己的method參數來區分是什麼方法。
Object | invoke(Object proxy,Method method,Object[] args) 在代理實例上處理方法調用並返回結果。 |
講的有點抽象,下面通過一個實例來演示一下吧:
JDK動態代理示例
現在定義兩個接口Vehicle和Rechargable,Vehicle表示交通工具類,有drive()方法;Rechargable接口表示可充電的(工具),有recharge() 方法;
定義一個實現兩個接口的類ElectricCar,類圖如下:
通過下面的代碼片段,來爲ElectricCar創建動態代理類:
- package com.foo.proxy;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Proxy;
- public class Test {
- public static void main(String[] args) {
- ElectricCar car = new ElectricCar();
- // 1.獲取對應的ClassLoader
- ClassLoader classLoader = car.getClass().getClassLoader();
- // 2.獲取ElectricCar 所實現的所有接口
- Class[] interfaces = car.getClass().getInterfaces();
- // 3.設置一個來自代理傳過來的方法調用請求處理器,處理所有的代理對象上的方法調用
- InvocationHandler handler = new InvocationHandlerImpl(car);
- /*
- 4.根據上面提供的信息,創建代理對象 在這個過程中,
- a.JDK會通過根據傳入的參數信息動態地在內存中創建和.class 文件等同的字節碼
- b.然後根據相應的字節碼轉換成對應的class,
- c.然後調用newInstance()創建實例
- */
- Object o = Proxy.newProxyInstance(classLoader, interfaces, handler);
- Vehicle vehicle = (Vehicle) o;
- vehicle.drive();
- Rechargable rechargeable = (Rechargable) o;
- rechargeable.recharge();
- }
- }
package com.foo.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
ElectricCar car = new ElectricCar();
// 1.獲取對應的ClassLoader
ClassLoader classLoader = car.getClass().getClassLoader();
// 2.獲取ElectricCar 所實現的所有接口
Class[] interfaces = car.getClass().getInterfaces();
// 3.設置一個來自代理傳過來的方法調用請求處理器,處理所有的代理對象上的方法調用
InvocationHandler handler = new InvocationHandlerImpl(car);
/*
4.根據上面提供的信息,創建代理對象 在這個過程中,
a.JDK會通過根據傳入的參數信息動態地在內存中創建和.class 文件等同的字節碼
b.然後根據相應的字節碼轉換成對應的class,
c.然後調用newInstance()創建實例
*/
Object o = Proxy.newProxyInstance(classLoader, interfaces, handler);
Vehicle vehicle = (Vehicle) o;
vehicle.drive();
Rechargable rechargeable = (Rechargable) o;
rechargeable.recharge();
}
}
- package com.foo.proxy;
- /**
- * 交通工具接口
- * @author louluan
- */
- public interface Vehicle {
- public void drive();
- }
package com.foo.proxy;
/**
* 交通工具接口
* @author louluan
*/
public interface Vehicle {
public void drive();
}
- package com.foo.proxy;
- /**
- * 可充電設備接口
- * @author louluan
- */
- public interface Rechargable {
- public void recharge();
- }
package com.foo.proxy;
/**
* 可充電設備接口
* @author louluan
*/
public interface Rechargable {
public void recharge();
}
- package com.foo.proxy;
- /**
- * 電能車類,實現Rechargable,Vehicle接口
- * @author louluan
- */
- public class ElectricCar implements Rechargable, Vehicle {
- @Override
- public void drive() {
- System.out.println("Electric Car is Moving silently...");
- }
- @Override
- public void recharge() {
- System.out.println("Electric Car is Recharging...");
- }
- }
package com.foo.proxy;
/**
* 電能車類,實現Rechargable,Vehicle接口
* @author louluan
*/
public class ElectricCar implements Rechargable, Vehicle {
@Override
public void drive() {
System.out.println("Electric Car is Moving silently...");
}
@Override
public void recharge() {
System.out.println("Electric Car is Recharging...");
}
}
- package com.foo.proxy;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- public class InvocationHandlerImpl implements InvocationHandler {
- private ElectricCar car;
- public InvocationHandlerImpl(ElectricCar car)
- {
- this.car=car;
- }
- @Override
- public Object invoke(Object paramObject, Method paramMethod,
- Object[] paramArrayOfObject) throws Throwable {
- System.out.println("You are going to invoke "+paramMethod.getName()+" ...");
- paramMethod.invoke(car, null);
- System.out.println(paramMethod.getName()+" invocation Has Been finished...");
- return null;
- }
- }
package com.foo.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class InvocationHandlerImpl implements InvocationHandler {
private ElectricCar car;
public InvocationHandlerImpl(ElectricCar car)
{
this.car=car;
}
@Override
public Object invoke(Object paramObject, Method paramMethod,
Object[] paramArrayOfObject) throws Throwable {
System.out.println("You are going to invoke "+paramMethod.getName()+" ...");
paramMethod.invoke(car, null);
System.out.println(paramMethod.getName()+" invocation Has Been finished...");
return null;
}
}
來看一下代碼執行後的結果:
生成動態代理類的字節碼並且保存到硬盤中:
JDK提供了sun.misc.ProxyGenerator.generateProxyClass(String proxyName,class[] interfaces) 底層方法來產生動態代理類的字節碼:
下面定義了一個工具類,用來將生成的動態代理類保存到硬盤中:
- package com.foo.proxy;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.lang.reflect.Proxy;
- import sun.misc.ProxyGenerator;
- public class ProxyUtils {
- /*
- * 將根據類信息 動態生成的二進制字節碼保存到硬盤中,
- * 默認的是clazz目錄下
- * params :clazz 需要生成動態代理類的類
- * proxyName : 爲動態生成的代理類的名稱
- */
- public static void generateClassFile(Class clazz,String proxyName)
- {
- //根據類信息和提供的代理類名稱,生成字節碼
- byte[] classFile = ProxyGenerator.generateProxyClass(proxyName, clazz.getInterfaces());
- String paths = clazz.getResource(".").getPath();
- System.out.println(paths);
- FileOutputStream out = null;
- try {
- //保留到硬盤中
- out = new FileOutputStream(paths+proxyName+".class");
- out.write(classFile);
- out.flush();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
package com.foo.proxy;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
import sun.misc.ProxyGenerator;
public class ProxyUtils {
/*
* 將根據類信息 動態生成的二進制字節碼保存到硬盤中,
* 默認的是clazz目錄下
* params :clazz 需要生成動態代理類的類
* proxyName : 爲動態生成的代理類的名稱
*/
public static void generateClassFile(Class clazz,String proxyName)
{
//根據類信息和提供的代理類名稱,生成字節碼
byte[] classFile = ProxyGenerator.generateProxyClass(proxyName, clazz.getInterfaces());
String paths = clazz.getResource(".").getPath();
System.out.println(paths);
FileOutputStream out = null;
try {
//保留到硬盤中
out = new FileOutputStream(paths+proxyName+".class");
out.write(classFile);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
現在我們想將生成的代理類起名爲“ElectricCarProxy”,並保存在硬盤,應該使用以下語句:
ProxyUtils.generateClassFile(car.getClass(), "ElectricCarProxy");
這樣將在ElectricCar.class 同級目錄下產生 ElectricCarProxy.class文件。用反編譯工具如jd-gui.exe 打開,將會看到以下信息:
- import com.foo.proxy.Rechargable;
- import com.foo.proxy.Vehicle;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.lang.reflect.UndeclaredThrowableException;
- /**
- 生成的動態代理類的組織模式是繼承Proxy類,然後實現需要實現代理的類上的所有接口,而在實現的過程中,則是通過將所有的方法都交給了InvocationHandler來處理
- */
- public final class ElectricCarProxy extends Proxy
- implements Rechargable, Vehicle
- {
- private static Method m1;
- private static Method m3;
- private static Method m4;
- private static Method m0;
- private static Method m2;
- public ElectricCarProxy(InvocationHandler paramInvocationHandler)
- throws
- {
- super(paramInvocationHandler);
- }
- public final boolean equals(Object paramObject)
- throws
- {
- try
- { // 方法功能實現交給InvocationHandler處理
- return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
- }
- catch (Error|RuntimeException localError)
- {
- throw localError;
- }
- catch (Throwable localThrowable)
- {
- throw new UndeclaredThrowableException(localThrowable);
- }
- }
- public final void recharge()
- throws
- {
- try
- {
- // 方法功能實現交給InvocationHandler處理
- this.h.invoke(this, m3, null);
- return;
- }
- catch (Error|RuntimeException localError)
- {
- throw localError;
- }
- catch (Throwable localThrowable)
- {
- throw new UndeclaredThrowableException(localThrowable);
- }
- }
- public final void drive()
- throws
- {
- try
- {
- // 方法功能實現交給InvocationHandler處理
- this.h.invoke(this, m4, null);
- return;
- }
- catch (Error|RuntimeException localError)
- {
- throw localError;
- }
- catch (Throwable localThrowable)
- {
- throw new UndeclaredThrowableException(localThrowable);
- }
- }
- public final int hashCode()
- throws
- {
- try
- {
- // 方法功能實現交給InvocationHandler處理
- return ((Integer)this.h.invoke(this, m0, null)).intValue();
- }
- catch (Error|RuntimeException localError)
- {
- throw localError;
- }
- catch (Throwable localThrowable)
- {
- throw new UndeclaredThrowableException(localThrowable);
- }
- }
- public final String toString()
- throws
- {
- try
- {
- // 方法功能實現交給InvocationHandler處理
- return (String)this.h.invoke(this, m2, null);
- }
- catch (Error|RuntimeException localError)
- {
- throw localError;
- }
- catch (Throwable localThrowable)
- {
- throw new UndeclaredThrowableException(localThrowable);
- }
- }
- static
- {
- try
- { //爲每一個需要方法對象,當調用相應的方法時,分別將方法對象作爲參數傳遞給InvocationHandler處理
- m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
- m3 = Class.forName("com.foo.proxy.Rechargable").getMethod("recharge", new Class[0]);
- m4 = Class.forName("com.foo.proxy.Vehicle").getMethod("drive", new Class[0]);
- m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
- m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
- return;
- }
- catch (NoSuchMethodException localNoSuchMethodException)
- {
- throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
- }
- catch (ClassNotFoundException localClassNotFoundException)
- {
- throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
- }
- }
- }
import com.foo.proxy.Rechargable;
import com.foo.proxy.Vehicle;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
/**
生成的動態代理類的組織模式是繼承Proxy類,然後實現需要實現代理的類上的所有接口,而在實現的過程中,則是通過將所有的方法都交給了InvocationHandler來處理
*/
public final class ElectricCarProxy extends Proxy
implements Rechargable, Vehicle
{
private static Method m1;
private static Method m3;
private static Method m4;
private static Method m0;
private static Method m2;
public ElectricCarProxy(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
throws
{
try
{ // 方法功能實現交給InvocationHandler處理
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void recharge()
throws
{
try
{
// 方法功能實現交給InvocationHandler處理
this.h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void drive()
throws
{
try
{
// 方法功能實現交給InvocationHandler處理
this.h.invoke(this, m4, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final int hashCode()
throws
{
try
{
// 方法功能實現交給InvocationHandler處理
return ((Integer)this.h.invoke(this, m0, null)).intValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final String toString()
throws
{
try
{
// 方法功能實現交給InvocationHandler處理
return (String)this.h.invoke(this, m2, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
static
{
try
{ //爲每一個需要方法對象,當調用相應的方法時,分別將方法對象作爲參數傳遞給InvocationHandler處理
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m3 = Class.forName("com.foo.proxy.Rechargable").getMethod("recharge", new Class[0]);
m4 = Class.forName("com.foo.proxy.Vehicle").getMethod("drive", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}
仔細觀察可以看出生成的動態代理類有以下特點:
1.繼承自 java.lang.reflect.Proxy,實現了 Rechargable,Vehicle 這兩個ElectricCar實現的接口;
2.類中的所有方法都是final 的;
3.所有的方法功能的實現都統一調用了InvocationHandler的invoke()方法。
cglib 生成動態代理類的機制----通過類繼承:
JDK中提供的生成動態代理類的機制有個鮮明的特點是: 某個類必須有實現的接口,而生成的代理類也只能代理某個類接口定義的方法,比如:如果上面例子的ElectricCar實現了繼承自兩個接口的方法外,另外實現了方法bee() ,則在產生的動態代理類中不會有這個方法了!更極端的情況是:如果某個類沒有實現接口,那麼這個類就不能同JDK產生動態代理了!
幸好我們有cglib。“CGLIB(Code Generation Library),是一個強大的,高性能,高質量的Code生成類庫,它可以在運行期擴展Java類與實現Java接口。”
cglib 創建某個類A的動態代理類的模式是:
1. 查找A上的所有非final 的public類型的方法定義;
2. 將這些方法的定義轉換成字節碼;
3. 將組成的字節碼轉換成相應的代理的class對象;
4. 實現 MethodInterceptor接口,用來處理 對代理類上所有方法的請求(這個接口和JDK動態代理InvocationHandler的功能和角色是一樣的)
一個有趣的例子:定義一個Programmer類,一個Hacker類
- package samples;
- /**
- * 程序猿類
- * @author louluan
- */
- public class Programmer {
- public void code()
- {
- System.out.println("I'm a Programmer,Just Coding.....");
- }
- }
package samples;
/**
* 程序猿類
* @author louluan
*/
public class Programmer {
public void code()
{
System.out.println("I'm a Programmer,Just Coding.....");
}
}
- package samples;
- import java.lang.reflect.Method;
- import net.sf.cglib.proxy.MethodInterceptor;
- import net.sf.cglib.proxy.MethodProxy;
- /*
- * 實現了方法攔截器接口
- */
- public class Hacker implements MethodInterceptor {
- @Override
- public Object intercept(Object obj, Method method, Object[] args,
- MethodProxy proxy) throws Throwable {
- System.out.println("**** I am a hacker,Let's see what the poor programmer is doing Now...");
- proxy.invokeSuper(obj, args);
- System.out.println("**** Oh,what a poor programmer.....");
- return null;
- }
- }
package samples;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/*
* 實現了方法攔截器接口
*/
public class Hacker implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("**** I am a hacker,Let's see what the poor programmer is doing Now...");
proxy.invokeSuper(obj, args);
System.out.println("**** Oh,what a poor programmer.....");
return null;
}
}
- package samples;
- import net.sf.cglib.proxy.Enhancer;
- public class Test {
- public static void main(String[] args) {
- Programmer progammer = new Programmer();
- Hacker hacker = new Hacker();
- //cglib 中加強器,用來創建動態代理
- Enhancer enhancer = new Enhancer();
- //設置要創建動態代理的類
- enhancer.setSuperclass(progammer.getClass());
- // 設置回調,這裏相當於是對於代理類上所有方法的調用,都會調用CallBack,而Callback則需要實行intercept()方法進行攔截
- enhancer.setCallback(hacker);
- Programmer proxy =(Programmer)enhancer.create();
- proxy.code();
- }
- }
package samples;
import net.sf.cglib.proxy.Enhancer;
public class Test {
public static void main(String[] args) {
Programmer progammer = new Programmer();
Hacker hacker = new Hacker();
//cglib 中加強器,用來創建動態代理
Enhancer enhancer = new Enhancer();
//設置要創建動態代理的類
enhancer.setSuperclass(progammer.getClass());
// 設置回調,這裏相當於是對於代理類上所有方法的調用,都會調用CallBack,而Callback則需要實行intercept()方法進行攔截
enhancer.setCallback(hacker);
Programmer proxy =(Programmer)enhancer.create();
proxy.code();
}
}
程序執行結果:
讓我們看看通過cglib生成的class文件內容:
- package samples;
- import java.lang.reflect.Method;
- import net.sf.cglib.core.ReflectUtils;
- import net.sf.cglib.core.Signature;
- import net.sf.cglib.proxy.Callback;
- import net.sf.cglib.proxy.Factory;
- import net.sf.cglib.proxy.MethodInterceptor;
- import net.sf.cglib.proxy.MethodProxy;
- public class Programmer
fa7aa2cd extends Programmer
EnhancerByCGLIB - implements Factory
- {
- //......省略
- private MethodInterceptor CGLIB$CALLBACK_0; // Enchaner傳入的methodInterceptor
- // ....省略
- public final void code()
- {
- MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
- if (tmp4_1 == null)
- {
- tmp4_1;
- CGLIB$BIND_CALLBACKS(this);//若callback 不爲空,則調用methodInterceptor 的intercept()方法
- }
- if (this.CGLIB$CALLBACK_0 != null)
- return;
- //如果沒有設置callback回調函數,則默認執行父類的方法
- super.code();
- }
- //....後續省略
- }
package samples;
import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class Programmer$$EnhancerByCGLIB$$fa7aa2cd extends Programmer
implements Factory
{
//......省略
private MethodInterceptor CGLIB$CALLBACK_0; // Enchaner傳入的methodInterceptor
// ....省略
public final void code()
{
MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
if (tmp4_1 == null)
{
tmp4_1;
CGLIB$BIND_CALLBACKS(this);//若callback 不爲空,則調用methodInterceptor 的intercept()方法
}
if (this.CGLIB$CALLBACK_0 != null)
return;
//如果沒有設置callback回調函數,則默認執行父類的方法
super.code();
}
//....後續省略
}