1. 程式人生 > 實用技巧 >VisualVM實現不中斷程式和修改程式碼的前提下列印函式的入參和返回值

VisualVM實現不中斷程式和修改程式碼的前提下列印函式的入參和返回值

在VisualVM中下載BTrace外掛

安裝此外掛並激活

寫除錯程式

public class BTraceTest {

    public int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) throws IOException {
        BTraceTest test = new BTraceTest();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        for (int i=0; i < 10; i++) {
            reader.readLine();
            int a = (int) Math.round(Math.random() * 1000);
            int b = (int) Math.round(Math.random() * 1000);
            System.out.println(test.add(a, b));
        }
    }

}

執行並寫在BTrace中寫除錯程式

用VisualVM模式下進行除錯

找到執行的程式

右擊新增BTrace除錯程式碼

/* BTrace Script Template */
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;

@BTrace
public class TracingScript {
	/* put your code here */
  @OnMethod(
      clazz="com.baiyuliuguang.test.JVMTest.BTraceTest",
      method="add",
      location=@Location(Kind.RETURN)
    )
    public static void func(@Self com.baiyuliuguang.test.JVMTest.BTraceTest instance,int a, int b,@Return int result){
          
          println("呼叫堆疊:");
          jstack();
          println(strcat("方法引數A:", str(a)));
          println(strcat("方法引數B:", str(b)));
          println(strcat("方法結果:", str(result)));
        }
}

點選start開啟除錯

執行結果

可以對比看到執行結果與BTrace除錯輸出結果一致,但是我們沒有增加任何原始碼,只需要在BTrace中增加除錯即可。