本例將示範如何使用 FragmentAtClassScope 探針片段。
在本範例中,探針會計算套件中所有符合 "com.sample*" 萬用字元型樣之類別的所有實例數目,然後每建立一百個就報告一次。
"fragment at class scope" 的目的是宣告一個計數器,它在編入 entry 片段之類別中,是以 int-type 靜態欄位的形式出現。 該片段也會為 fragment 類別宣告一個靜態起始設定程式,報告該探針已經載入。 請注意,fragmentAtClassScope 區段中的項目,是內建在所產生的探針類別中,而不是在套用探針的類別中。 如果要把靜態欄位或靜態起始設定程式邏輯,插入到套用探針的類別中, 請使用 staticField 和 staticInitializer 物件。
如果要使用這個程式碼範例,請把目標物件中的 package="com.sample*",改為參照實際的套件名稱。
請注意,如果要在 XML 中使用 & 和 < 字元,必須指定字元實體 & 和 <,如本例所示。
<?xml version="1.0" encoding="ASCII"?>
<probekit>
<probe>
<fragmentAtClassScope>
static public int entry_counter = 0;
static int counter = 0;
static { System.out.println("[fragmentAtClassScope sample probe has loaded.]"); }
</fragmentAtClassScope>
<target type="include" package="com.sample*" method="<init>" />
<target type="exclude" package="*" />
<fragment type="entry">
<code>
++counter;
if (counter % 100 == 0)
System.out.println("[" + counter + " instances of classes in com.sample package so far]");
</code>
</fragment>
</probe>
</probekit>
母主題: Probekit 範例