JAVA自定义Annotation

  • Annotation定义
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation {
    String name() default  "li";
    String age();
    int[] arrayAttr() default {1,2,3};
}
  • Annotation使用
@MyAnnotation(age = "11")
public class AnnotationTest {

    public static void main(String[] args) {
        if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){
            MyAnnotation annotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
            System.out.println(annotation.name());
            System.out.println(annotation.age());
            System.out.println(annotation.arrayAttr()[0]);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40990732/article/details/80974742
今日推荐