staticField and staticInitializer example
This example demonstrates the use of the staticField data item and the StaticInitializer probe fragment.
In this example, a probe keeps track of when instances of a class are created. If an instance is created more than one second after the previous instance of that class, the probe writes a log message.
Here is what this probe does:
- Using the staticField data item, the probe creates a static field of type Date in every probed class. The static field will be initialized by calling new Date();.
- In the staticInitializer fragment, the probe sets the Date instance of a probed class to "time zero" (January, 1970) when it is loaded.
- In the entry fragment (because of the target rules, the entry fragment executes only in constructors), the probe checks to see when the previous update was performed, and issues a report if the update was performed more than a second ago.
- Finally, the probe updates the value of the Date instance to "now."
This probe uses staticField to create a new static field in every probed class. By comparison, using fragmentAtClassScope to declare the Date field would result in a single instance of Date appearing in the generated class that holds the probe fragments, no matter how many classes the probe is applied to. You can do this if you want to track the time delay between creation of instances of any probed class, instead of tracking the delay between the creation of instances of each probed class.
To use this example code, change package="com.sample*" in the target object to refer to an actual package name.
Note that to use the characters & and < in XML, specify the character entities & and <, as shown in the example.
<?xml version="1.0" encoding="ASCII"?> <probekit> <probe> <target type="include" package="com.sample*" method="<init>" /> <target type="exclude" package="*" /> <staticField type="java.util.Date"/> <fragment type="entry"> <data name="lastInstanceDate" type="staticField"/> <data name="clname"/> <code> java.util.Date d = new java.util.Date(); long now = d.getTime(); long prev = lastInstanceDate.getTime(); if (prev != 0 && prev + 1000 < now) { System.out.println("[" + clname + " instance after > 1 second]"); } lastInstanceDate.setTime(now); </code> </fragment> <fragment type="staticInitializer"> <data name="lastInstanceDate" type="staticField"/> <data name="clname"/> <code> lastInstanceDate.setTime(0); System.out.println("[" + clname + " class loaded]"); </code> </fragment> </probe> </probekit>
Parent topic
Probekit Examples
Related reference
The StaticField probe object
The staticInitializer probe fragment