这两天比较无聊,随便找点东西进行学习。目标就瞄准了javassist。关于javassist的介绍google一下,这里也不介绍了。
?
对于某一个类,直接在编译好的.class文件插入一些内容。
?
比如:
package test.param;
public class Screen {
public void draw(int i , int j){
System.out.println("move to i,j");
}
}
?对于这个对象,我现在想在输出之前,把i,和j的值输出出来。如何使用javassist进行操作呢?
?
package test.param;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
public class Test {
public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.get("test.param.Screen");
CtMethod ctm = ctClass.getDeclaredMethod("draw");
ctm.insertBefore("{System.out.println(\"i=\"+($1)+\",j=\"+$2);}");
ctClass.writeFile();//这里我不知道为什么写不到文件里,很纳闷。
Method m = ctClass.toClass().getMethod("draw",Integer.TYPE,Integer.TYPE);
Screen s = new Screen();
m.invoke(s, 1,2);
}
}
?执行这个main方法的时候,输出结果就是这样:
i=1,j=2
move to i,j
一个简单的例子,稍微熟悉一下javassist.