在程序运行期间,注入调试代码,注入代码对程序变量只读,且不能调用函数
~/Downloads/btrace-bin-1.3.5/bin/btrace 48650 TraceMethodArgsAndReturn.java
<dependency> <groupId>com.sun.tools.btrace</groupId> <artifactId>btrace-agent</artifactId> <version>1.0.5</version> </dependency> <dependency> <groupId>com.sun.tools.btrace</groupId> <artifactId>btrace-boot</artifactId> <version>1.0.5</version> </dependency>
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; } }
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(); } }