実行時にアノテーションの情報を利用するときは、@Retention(RetentionPolicy.RUNTIME)を忘れずに。 2009/01/16




アノテーションを設定して、実行時にチェックしたいなぁと考えました。
@Retention(RetentionPolicy.RUNTIME)を設定することせずに、getClass().getDeclaredMethods()を使って、Methodごとのアノテーション情報を実行時に取得してチェックしようとしました。

Annotation[] annotations = method.getDeclaredAnnotations();

で、設定したアノテーション情報が取得できない場合は、定義したアノテーションクラスに、@Retention(RetentionPolicy.RUNTIME)を設定しているかチェックすべしです。

package ql;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Nonnull {}

: