public class Point {
int x, y;
void move(int dx, int dy) { x += dx; y += dy; }
}
public static void main(String[] args) throws Exception{
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("com.kq.javassist.entity.Point");
CtMethod m = cc.getDeclaredMethod("move");
m.insertBefore("{ System.out.println($1); System.out.println($2); }");
cc.writeFile("D:\\javassist\\");
}
生成class
package com.kq.javassist.entity;
import java.io.PrintStream;
public class Point
{
int x;
int y;
void move(int dx, int dy)
{
System.out.println(dx);System.out.println(dy);this.x += dx;this.y += dy;
}
}
$1 and $2 are replaced with dx and dy, respectively.
$1, $2, $3 ... are updatable. If a new value is assigend to one of those variables, then the value of the parameter represented by that variable is also updated