1、什麼是ASMjava
ASM是一個java字節碼操縱框架,它能被用來動態生成類或者加強既有類的功能。ASM 能夠直接產生二進制 class 文件,也能夠在類被加載入 Java 虛擬機以前動態改變類行爲。Java class 被存儲在嚴格格式定義的 .class文件裏,這些類文件擁有足夠的元數據來解析類中的全部元素:類名稱、方法、屬性以及 Java 字節碼(指令)。ASM從類文件中讀入信息後,可以改變類行爲,分析類信息,甚至可以根據用戶要求生成新類。web
使用ASM框架須要導入asm的jar包,下載連接:asm-3.2.jar。數組
2、如何使用ASM框架
ASM框架中的核心類有如下幾個:ide
① ClassReader:該類用來解析編譯過的class字節碼文件。測試
② ClassWriter:該類用來從新構建編譯後的類,好比說修改類名、屬性以及方法,甚至能夠生成新的類的字節碼文件。spa
③ ClassAdapter:該類也實現了ClassVisitor接口,它將對它的方法調用委託給另外一個ClassVisitor對象。code
示例1.經過asm生成類的字節碼對象
1 package com.asm3; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 8 import org.objectweb.asm.ClassWriter; 9 import org.objectweb.asm.Opcodes;10 11 /**12 * 經過asm生成類的字節碼13 * @author Administrator14 *15 */16 public class GeneratorClass {17 18 public static void main(String[] args) throws IOException {19 //生成一個類只須要ClassWriter組件便可20 ClassWriter cw = new ClassWriter(0);21 //經過visit方法肯定類的頭部信息22 cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC+Opcodes.ACC_ABSTRACT+Opcodes.ACC_INTERFACE,23 "com/asm3/Comparable", null, "java/lang/Object", new String[]{"com/asm3/Mesurable"});24 //定義類的屬性25 cw.visitField(Opcodes.ACC_PUBLIC+Opcodes.ACC_FINAL+Opcodes.ACC_STATIC,26 "LESS", "I", null, new Integer(-1)).visitEnd();27 cw.visitField(Opcodes.ACC_PUBLIC+Opcodes.ACC_FINAL+Opcodes.ACC_STATIC,28 "EQUAL", "I", null, new Integer(0)).visitEnd();29 cw.visitField(Opcodes.ACC_PUBLIC+Opcodes.ACC_FINAL+Opcodes.ACC_STATIC,30 "GREATER", "I", null, new Integer(1)).visitEnd();31 //定義類的方法32 cw.visitMethod(Opcodes.ACC_PUBLIC+Opcodes.ACC_ABSTRACT, "compareTo",33 "(Ljava/lang/Object;)I", null, null).visitEnd();34 cw.visitEnd(); //使cw類已經完成35 //將cw轉換成字節數組寫到文件裏面去36 byte[] data = cw.toByteArray();37 File file = new File("D://Comparable.class");38 FileOutputStream fout = new FileOutputStream(file);39 fout.write(data);40 fout.close();41 }42 }
生成一個類的字節碼文件只須要用到ClassWriter類便可,生成Comparable.class後用javap指令對其進行反編譯:javap -c Comparable.class >test.txt ,編譯後的結果以下:blog
1 public interface com.asm3.Comparable extends com.asm3.Mesurable {2 public static final int LESS;3 4 public static final int EQUAL;5 6 public static final int GREATER;7 8 public abstract int compareTo(java.lang.Object);9 }
注:一個編譯後的java類不包含package和import段,所以在class文件中全部的類型都使用的是全路徑。
示例2.修改類的字節碼文件
C.java
1 package com.asm5;2 3 public class C {4 public void m() throws InterruptedException{5 Thread.sleep(100); 6 }7 }
將C.java類的內容改成以下:
1 package com.asm5; 2 3 public class C { 4 public static long timer; 5 public void m() throws InterruptedException{ 6 timer -= System.currentTimeMillis(); 7 Thread.sleep(100); 8 timer += System.currentTimeMillis(); 9 }10 }
爲了弄清楚ASM是如何實現的,咱們先編譯這兩個類,而後比對它們的TraceClassVisitor的輸出,咱們能夠發現以下的不一樣(粗體表示)
GETSTATIC C.timer : J
INVOKESTATIC java/lang/System.currentTimilis()J
LSUB
PUTSTATIC C.timer : J
LDC 100
INVOKESTATIC java/lang/Thread.sleep(J)V
GETSTATIC C.timer : J
INVOKESTATIC java/lang/System.currentTimilis()J
LADD
PUTSTATIC C.timer : J
RETURN
MAXSTACK=4
MAXLOCALS=1
經過比對上面的指令,咱們能夠發現必須在m()方法的最前面增長四條指令,在RETURN指令前也增長四條指令,同時這四條必須位於xRETURN和ATHROW以前,由於這些指令都會結束方法的執行。
具體代碼以下:
AddTimeClassAdapter.java
1 package com.asm5; 2 3 import org.objectweb.asm.ClassAdapter; 4 import org.objectweb.asm.ClassVisitor; 5 import org.objectweb.asm.FieldVisitor; 6 import org.objectweb.asm.MethodAdapter; 7 import org.objectweb.asm.MethodVisitor; 8 import org.objectweb.asm.Opcodes; 9 10 public class AddTimeClassAdapter extends ClassAdapter {11 private String owner;12 private boolean isInterface;13 public AddTimeClassAdapter(ClassVisitor cv) {14 super(cv);15 }16 @Override17 public void visit(int version, int access, String name, String signature,18 String superName, String[] interfaces) {19 cv.visit(version, access, name, signature, superName, interfaces);20 owner = name;21 isInterface = (access & Opcodes.ACC_INTERFACE) != 0;22 }23 @Override24 public MethodVisitor visitMethod(int access, String name, String desc,25 String signature, String[] exceptions) {26 MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);27 if(!name.equals("<init>") && !isInterface && mv!=null){28 //爲方法添加計時功能29 mv = new AddTimeMethodAdapter(mv);30 }31 return mv;32 }33 @Override34 public void visitEnd() {35 //添加字段36 if(!isInterface){37 FieldVisitor fv = cv.visitField(Opcodes.ACC_PUBLIC+Opcodes.ACC_STATIC, "timer", "J", null, null);38 if(fv!=null){39 fv.visitEnd();40 }41 }42 cv.visitEnd();43 }44 45 class AddTimeMethodAdapter extends MethodAdapter{46 public AddTimeMethodAdapter(MethodVisitor mv) {47 super(mv);48 }49 @Override50 public void visitCode() {51 mv.visitCode();52 mv.visitFieldInsn(Opcodes.GETSTATIC, owner, "timer", "J");53 mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J");54 mv.visitInsn(Opcodes.LSUB);55 mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, "timer", "J");56 }57 @Override58 public void visitInsn(int opcode) {59 if((opcode>=Opcodes.IRETURN && opcode<=Opcodes.RETURN) || opcode==Opcodes.ATHROW){60 mv.visitFieldInsn(Opcodes.GETSTATIC, owner, "timer", "J");61 mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J");62 mv.visitInsn(Opcodes.LADD);63 mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, "timer", "J");64 }65 mv.visitInsn(opcode);66 }67 @Override68 public void visitMaxs(int maxStack, int maxLocal) {69 mv.visitMaxs(maxStack+4, maxLocal);70 }71 }72 73 }
Generator.java
1 package com.asm5; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 8 import org.objectweb.asm.ClassAdapter; 9 import org.objectweb.asm.ClassReader;10 import org.objectweb.asm.ClassWriter;11 12 13 14 public class Generator {15 16 public static void main(String[] args){17 try {18 ClassReader cr = new ClassReader("com/asm5/C");19 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);20 ClassAdapter classAdapter = new AddTimeClassAdapter(cw);21 //使給定的訪問者訪問Java類的ClassReader22 cr.accept(classAdapter, ClassReader.SKIP_DEBUG);23 byte[] data = cw.toByteArray();24 File file = new File(System.getProperty("user.dir") + "\\WebRoot\\WEB-INF\\classes\\com\\asm5\\C.class");25 FileOutputStream fout = new FileOutputStream(file);26 fout.write(data);27 fout.close();28 System.out.println("success!");29 } catch (FileNotFoundException e) {30 e.printStackTrace();31 } catch (IOException e) {32 e.printStackTrace();33 }34 }35 36 }
下面是一個測試類:
1 package com.asm5; 2 3 public class Test { 4 public static void main(String[] args) throws InterruptedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { 5 C c = new C(); 6 c.m(); 7 Class cc = c.getClass(); 8 System.out.println(cc.getField("timer").get(c)); 9 }10 }
輸出結果爲:100