在程序运行期间,注入调试代码,注入代码对程序变量只读,且不能调用函数 ===== 使用方法 ===== - 下载btrace程序 - 查找要注入的程序的pid - 编写btrace代码 - 开始注入~/Downloads/btrace-bin-1.3.5/bin/btrace 48650 TraceMethodArgsAndReturn.java - 48650 是主程序的pid ==== maven ==== com.sun.tools.btrace btrace-agent 1.0.5 com.sun.tools.btrace btrace-boot 1.0.5 ==== main ==== import java.util.Random; public class CaseObject { private static int sleepTotalTime = 0; public static void main(String[] args) throws Exception { Random random = new Random(); CaseObject object = new CaseObject(); boolean result = true; while (result) { result = object.execute(random.nextInt(1000)); Thread.sleep(1000); } } public boolean execute(int sleepTime) throws Exception { System.out.println("sleep: " + sleepTime); sleepTotalTime += sleepTime; Thread.sleep(sleepTime); return true; } } ==== btrace ==== import static com.sun.btrace.BTraceUtils.*; import com.sun.btrace.annotations.*; @BTrace public class TraceMethodArgsAndReturn{ @OnMethod( clazz="CaseObject", method="execute", location=@Location(Kind.RETURN) ) public static void traceExecute(@Self Object instance,int sleepTime,@Return boolean result){ println("call CaseObject.execute"); println(strcat("sleepTime is:", str(sleepTime))); // 获取类的属性 int field = (Integer) get(field("CaseObject", "sleepTotalTime"), instance); println("sleepTotalTime is:"+field); println(strcat("return value is:", str(result))); // 查看调用栈 jstack(); } }