[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

:

匿名

@Inherited を MyAnnotation につけてやれば OK ですね。

ugo.nakawaka

ひえー
ありがとうございます。
確認しました。
@InheritedをつけてOKでした。
ありがとうございます。勉強になりましたです。