プログラマメモ2 - programmer no memo2

[java]あれーーー、匿名クラスのアノテーションは実行時につかないの? - いやつきます。 その2 2009/01/30

先日書いた記事(プログラマメモ2: [java]あれーーー、匿名クラスのアノテーションは実行時につかないの?)で、コメントをいただきまして、@Inheritedを使う事で解決。

うーん勉強になりました。

というわけで再びコード

package build;

import java.awt.Container;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class TestAnnotation {

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {

}


@MyAnnotation
static class MyContainer extends Container {

}

public static void main(String[] args) {

Container container = new MyContainer();
Container container2 = new MyContainer() {
};

System.out.println("*** not anonymous inner class:"
+ container.getClass().isAnnotationPresent(MyAnnotation.class));
System.out
.println("*** anonymous inner class:"
+ container2.getClass().isAnnotationPresent(
MyAnnotation.class));

}

}


結果は、
*** not anonymous inner class:true
*** anonymous inner class:true

[java]あれーーー、匿名クラスのアノテーションは実行時につかないの? 2009/01/28
2009/01/30

Javaアノテーション実験です。

匿名クラスにつけたアノテーションが実行時につかないっぽい。
使い方まちがってるかなぁ

追記
匿名さんからのコメントです。@Inheritedをつけるとオッケーでした!!


以下テストコード。

package build;

import java.awt.Container;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class TestAnnotation {

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {

}

@MyAnnotation
static class MyContainer extends Container {

}

public static void main(String[] args) {

Container container = new MyContainer();
Container container2 = new MyContainer() {
};

System.out.println("*** not anonymous inner class:"
+ container.getClass().isAnnotationPresent(MyAnnotation.class));
System.out.println("*** anonymous inner class:"
+ container2.getClass().isAnnotationPresent(MyAnnotation.class));

}

}


実行結果
*** not anonymous inner class:true
*** anonymous inner class:false

実行時にアノテーションの情報を利用するときは、@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 {}