8 カスタム注釈
イベントのカスタム注釈の作成は、Java注釈の作成と同じです。CustomAnnotationSample.java
の例でこれを示します。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import jdk.jfr.Description;
import jdk.jfr.Event;
import jdk.jfr.Label;
import jdk.jfr.MetadataDefinition;
import jdk.jfr.Name;
import jdk.jfr.Relational;
public class CustomAnnotationSample {
@MetadataDefinition
@Name("com.oracle.Severity")
@Label("Severity")
@Description("Value between 0 and 100 that indicates " +
"severity. 100 is most severe.")
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface Severity {
int value() default 50;
}
@MetadataDefinition
@Name("com.oracle.TransactionId")
@Label("Transaction ID")
@Relational
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface TransactionId { }
@Name("com.oracle.TransactionBlocked")
@Severity(80)
@Label("Transaction Blocked")
static class TransactionBlocked extends Event {
@TransactionId
@Label("Transaction")
long transaction;
@TransactionId
@Label("Transaction Blocker")
long transactionBlocker;
}
public static void main(String... args) {
TransactionBlocked event = new TransactionBlocked();
event.begin();
event.transaction = 1;
event.transactionBlocker = 2;
event.commit();
}
}
次のコマンドを使用して、CustomAnnotationSample
を実行します:
java -XX:StartFlightRecording:filename=ca.jfr CustomAnnotationSample.java
customannotationsample.jfr
のすべてのイベントに関する注釈、カテゴリ、フィールド・レイアウトおよびその他の情報を表示するには、次のコマンドを実行します:
jfr metadata ca.jfr
前のコマンドの出力は次のようになります:
@Name("com.oracle.Severity")
@Label("Severity")
@Description("Value between 0 and 100 that indicates severity. 100 is most severe.")
class Severity extends java.lang.annotation.Annotation {
int value;
}
@Name("com.oracle.TransactionId")
@Label("Transaction ID")
@Relational
class TransactionId extends java.lang.annotation.Annotation {
}
...
@Name("com.oracle.TransactionBlocked")
@Severity(80)
@Label("Transaction Blocked")
class TransactionBlocked extends jdk.jfr.Event {
@Label("Start Time")
@Timestamp("TICKS")
long startTime;
@Label("Duration")
@Timespan("TICKS")
long duration;
@Label("Event Thread")
@Description("Thread in which event was committed in")
Thread eventThread;
@Label("Stack Trace")
@Description("Stack Trace starting from the method the event was committed in")
StackTrace stackTrace;
@TransactionId
@Label("Transaction")
long transaction;
@TransactionId
@Label("Transaction Blocker")
long transactionBlocker;
}
カスタム注釈の値にアクセスするには、EventType.getAnnotationメソッドを使用しますが、このメソッドは、注釈型に対応するClassオブジェクトという引数を1つ取ります。たとえば、次のコードでは、重大度が50より大きいイベントが出力されます:
for (var e : RecordingFile.readAllEvents(file)) {
EventType t = e.getEventType();
Severity s = t.getAnnotation(Severity.class);
if (s != null && s.getValue() > 50) {
System.out.println(e);
}
}
Javaチュートリアルの注釈型の宣言を参照してください。