---
title: "BTrace工具实例应用"
author: "mgoann"
date: "2012-02-17T17:18:44Z"
tags: []
categories: ["编程语言"]
slug: "btrace"
draft: false
lastmod: "2012-02-17T17:53:13Z"
id: 1409676
url: "https://mgoann.iteye.com/blog/1409676"
---

**BTrace工具使用简介**

“Hello World”

案例描述

使用test方法接收一个int类型参数，根据参数放入map中两个字符串。

现代码中没有打印出任何的日志，导致产生的int值无法确定，以及执行路径无法确定，这个时候可以使用BTrace来跟踪、分析程序路径。

 

**import java.util.HashMap; import java.util.Map; import java.util.Random; public class TestHello { public static void main(String\[] args) throws InterruptedException { Thread.sleep(2000 * 10); TestHello th = new TestHello(); Random random = new Random(47); th.test(random.nextInt(9) + 1); } private Map&lt;String, String&gt; model = new HashMap&lt;String, String&gt;(); public boolean test(int age) { String variable1 = "默认提示信息:你输入的参数是：" + age; String variable2 = "欢迎观临网上乐园"; model.put("variable1", variable1); model.put("variable2", variable2); if (age &gt;= 1 && age &lt;= 5) { variable1 = "你的输入参数介于1和5之间"; variable2 = "欢迎小朋友玩益智类游戏"; model.put("variable1", variable1); model.put("variable2", variable2); return true; } else if (age &gt; 5 && age &lt;= 10) { variable1 = "你的输入参数介于5和10之间"; variable2 = "欢迎小朋友进入英语游乐场"; model.put("variable1", variable1); model.put("variable2", variable2); return false; } else { return true; } } }**

```

```

 

 

BTrace脚本：

 

import com.sun.btrace.annotations.\*; import static com.sun.btrace.BTraceUtils.\*; import java.util.HashMap; @BTrace public class BTraceField { @OnMethod(clazz="java.util.HashMap", method="put") public static void m(@Self HashMap map, Object Key, Object value) { // all calls to the methods with signature "()" println("===================="); print(Key); print(":"); println(value); } @OnMethod(clazz="TestHello", method="test") public static void d(@Self Object obj, int age){ print("test method is called, input age="); println(age); } }

```

```

 

首先运行TestHello

使用jps查找TestHello的PID，输入btrace &lt;pid&gt; BTraceField.java

 

输出：

test method is called, input age=3

====================

variable1:默认提示信息:你输入的参数是：3

====================

variable2:欢迎观临网上乐园

====================

variable1:你的输入参数介于1和5之间

====================

variable2:欢迎小朋友玩益智类游戏

 

其他相关博文

BTrace工具简介[http://mgoann.iteye.com/blog/1409667](http://mgoann.iteye.com/blog/1409667)  
BTrace实例应用[http://mgoann.iteye.com/blog/1409676](http://mgoann.iteye.com/blog/1409676)  
BTrace实际案例分析[http://mgoann.iteye.com/blog/1409685](http://mgoann.iteye.com/blog/1409685)