我有这个简单的功能:
public int id() {
return 0;
}
我有这个测试功能:
void test() {
int a = id();
int b = id();
int c = id();
int d = id();
int e = id();
int f = id();
System.out.println(a+" "+b+" "+c+" "+d+" "+e+" "+f);
}
我希望输出是1, 2, 3, 4, 5, 6
;
现在我呼吁instrument
哪个CtMethod
工作正常。
call to id! on line: 57
call to id! on line: 58
call to id! on line: 59
call to id! on line: 60
call to id! on line: 61
call to id! on line: 62
但最终所有的转换都没有任何效果。我不知道该怎么做,因为那里的信息太少了。
这是完整的代码:
package doeke.method_call_test;
import java.lang.instrument.Instrumentation;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
public class MethodCallTest {
static int id = 1;
public static void premain(String agentArgs, Instrumentation inst) {
try {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.getCtClass("doeke.method_call_test.MethodCallTest");
CtMethod[] methods = ctClass.getDeclaredMethods();
for (CtMethod cm : methods) {
cm.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {
if (m.getMethodName().equals("id")) {
// m.replace("{ $_ = "+id+"; }");
m.replace("$_ = 1; System.out.println(\"hello?\");");
System.out.println("call to id! on line: "+m.getLineNumber());
id++;
}
}
}
);
}
inst.retransformClasses(MethodCallTest.class);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MethodCallTest mct = new MethodCallTest();
mct.test();
}
void test() {
int a = id();
int b = id();
int c = id();
int d = id();
int e = id();
int f = id();
System.out.println(a+" "+b+" "+c+" "+d+" "+e+" "+f);
}
public int id() {
return 0;
}
}