javaassist 的使用
1
查看版本号:
F:\bisoft\ext\javassist-3.11.GA\javassist-3.11.0>java -jar javassist.jarJavassist version 3.11.0.GACopyright (C) 1999-2009 Shigeru Chiba. All Rights Reserved.F:\bisoft\ext\javassist-3.11.GA\javassist-3.11.0>
package cn.bisoft.java.util.test;import java.io.DataInputStream;import java.io.FileInputStream;import java.io.PrintWriter;import javassist.bytecode.ClassFile;import javassist.bytecode.ClassFileWriter;public class ClassDumpUtil{public static void dump(String classFilePath) throws Exception{DataInputStream in = new DataInputStream(new FileInputStream(classFilePath));ClassFile w = new ClassFile(in);PrintWriter out = new PrintWriter(System.out, true);out.println("*** constant pool ***");w.getConstPool().print(out);out.println();out.println("*** members ***");ClassFileWriter.print(w, out);}public static void main(String[] args) throws Exception {ClassDumpUtil.dump("E:/bisoft/code/workspace/bisoft/build/classes/cn/bisoft/java/core/F.class");}}
package sample;import javassist.*;public class Test{public int f(int i){return i + 1;}public static void main(String[] args) throws Exception{ClassPool pool = ClassPool.getDefault();CtClass cc = pool.get("sample.Test");try{cc.getDeclaredMethod("g");System.out.println("g() is already defined in sample.Test.");}catch (NotFoundException e){/* * getDeclaredMethod() throws an exception if g() is not defined in sample.Test. */CtMethod fMethod = cc.getDeclaredMethod("f");CtMethod gMethod = CtNewMethod.copy(fMethod, "g", cc, null);cc.addMethod(gMethod);cc.writeFile(); // update the class fileSystem.out.println("g() was added.");}}}
package sample;import java.io.PrintStream;import javassist.ClassPool;import javassist.CtClass;import javassist.CtMethod;import javassist.CtNewMethod;import javassist.NotFoundException;public class Test{ public int f(int i) { return (i + 1); } public static void main(String[] args) throws Exception { ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("sample.Test"); try { cc.getDeclaredMethod("g"); System.out.println("g() is already defined in sample.Test."); } catch (NotFoundException e) { CtMethod fMethod = cc.getDeclaredMethod("f"); CtMethod gMethod = CtNewMethod.copy(fMethod, "g", cc, null); cc.addMethod(gMethod); cc.writeFile(); System.out.println("g() was added."); } }[b] public int g(int i) { return (i + 1); }[/b]}