Java使用Javassist修改class文件
Contents
修改方法
package org.test;
/**
* Created by sky on 15-12-31.
*/
public class Bool {
public static void main(String[] args) throws InterruptedException {
new Bool().run();
}
public void run() throws InterruptedException {
Thread.sleep(1000 * 5);
System.out.println("default");
}
}
为方法前后添加性能统计时间
package org.javassist.demo;
import javassist.*;
import java.io.IOException;
/**
* Created by sky on 15-12-31.
*/
public class ReadByteCode {
public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException {
ClassPool classPool = ClassPool.getDefault();
classPool.importPackage("org.test");
CtClass ctClass = null;
try {
ctClass = classPool.get("org.test.Bool");
} catch (NotFoundException e) {
e.printStackTrace();
}
CtMethod[] methods = ctClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
CtMethod method = methods[i];
String methodName = method.getName();
String oldMethodName = methodName + "$$old";
if (!"main".equalsIgnoreCase(methodName)) {
CtMethod newMehtod = CtNewMethod.copy(method, ctClass, null);
method.setName(oldMethodName);
StringBuilder sb = new StringBuilder(100);
sb.append("{\nlong s = System.currentTimeMillis();\n");
sb.append(oldMethodName + "($$);\n");
sb.append("System.out.println(\"Call to method " + methodName
+ " took \" +\n (System.currentTimeMillis()-s) + "
+ "\" ms.\");\n");
sb.append("}");
newMehtod.setBody(sb.toString());
newMehtod.setName(methodName);
ctClass.addMethod(newMehtod);
}
}
ctClass.writeFile("/tmp/hello");
}
}
运行完后,就可以看到/tmp/hello
目录下有个class文件了,如下:
└─[0] <> tree /tmp/hello
/tmp/hello
└── org
└── test
└── Bool.class
2 directories, 1 file
运行结果如下:
└─[0] <> java org.test.Bool
default
Call to method run took 5001 ms.