例如一段这样的代码:
import java.util.Random; public class Case1{ 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 class CaseObject{ private static int sleepTotalTime=0; public boolean execute(int sleepTime) throws Exception{ System.out.println("sleep: "+sleepTime); sleepTotalTime+=sleepTime; Thread.sleep(sleepTime); return true; } }如在程序运行的情况下,想知道调用CaseObject的execute方法的以下几种情况,在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 CaseObject instance,int sleepTime,@Return boolean result){ println("call CaseObject.execute"); println(strcat("sleepTime is:",str(sleepTime))); println(strcat("sleepTotalTime is:",str(get(field("CaseObject","sleepTotalTime"),instance)))); println(strcat("return value is:",str(result))); } }然后直接执行btrace -cp btrace/build [pid] TraceMethodArgsAndReturn.java就可以了。
import static com.sun.btrace.BTraceUtils.; import com.sun.btrace.annotations.; @BTrace public class TraceMethodExecuteTime{ @TLS static long beginTime; @OnMethod( clazz="CaseObject", method="execute" ) public static void traceExecuteBegin(){ beginTime=timeMillis(); } @OnMethod( clazz="CaseObject", method="execute", location=@Location(Kind.RETURN) ) public static void traceExecute(int sleepTime,@Return boolean result){ println(strcat(strcat("CaseObject.execute time is:",str(timeMillis()-beginTime)),"ms")); } }3、谁调用了execute方法?
import static com.sun.btrace.BTraceUtils.; import com.sun.btrace.annotations.; @BTrace public class TraceMethodCallee{ @OnMethod( clazz="CaseObject", method="execute" ) public static void traceExecute(){ println("who call CaseObject.execute :"); jstack(); } }4、有没有人调用CaseObject中的哪一行代码?
import static com.sun.btrace.BTraceUtils.; import com.sun.btrace.annotations.; @BTrace public class TraceMethodLine{ @OnMethod( clazz="CaseObject", location=@Location(value=Kind.LINE,line=5) ) public static void traceExecute(@ProbeClassName String pcn,@ProbeMethodName String pmn,int line){ println(strcat(strcat(strcat("call ",pcn),"."),pmn)); } }从上面可看出,在有了BTrace后,要动态的跟踪代码的运行细节还是非常爽的,更多的细节的操作请大家查看BTrace的User Guide。