「Java入門」アノテーション@Retention、@Targetの使い方

1.RUNTIMEのアノテーション
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention( RetentionPolicy.RUNTIME )
@interface Runtime {}

2.CLASSのアノテーション
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention( RetentionPolicy.CLASS)
@interface Class {}

3.SOURCEのアノテーション
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention( RetentionPolicy.SOURCE )
@interface Source {}

4.mainコード
import java.lang.annotation.Annotation;
public class LstMethod {

@Runtime
@Class
@Source
class Annotated {}
public static void main ( String[] args ) {
// アノテーション一覧を表示
Annotation[] tc = Annotated.class.getAnnotations();
for ( int i = 0; i < tc.length; i++ ) {
System.out.println( tc[i].toString() );
}
}
}

5.@Targetのアノテーション
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

// 引数を指定
@Target({ElementType.FIELD, ElementType.PARAMETER })
public @interface Cmnn {}

Java

Posted by arkgame