annotation 注解

来源:互联网 发布:江苏软件行业协会 编辑:程序博客网 时间:2024/05/17 05:17

注解是对在程序中对类、字段、方法等的一个标记,比如@Override 注解,会在编译时检查这个注解是否重写了父类方法

Annotation 知识图
图片来自于网络

举个例子

@Target(ElementType.FIELD)    //设置注解作用类型@Documented                  //设置是否生成文档@Retention(RetentionPolicy.RUNTIME)  //设置作用周期@interface TestAnnotation {    String name()default "test";}class AnnotationUser{    @TestAnnotation()    String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}class Test{    public static void main(String[] args) {        AnnotationUser user = new AnnotationUser();        Field[] fs = AnnotationUser.class.getDeclaredFields();        for(Field a : fs){            System.out.println(a.getAnnotatedType().getType());            if(a.isAnnotationPresent(TestAnnotation.class)){                TestAnnotation annotation = a.getAnnotation(TestAnnotation.class);                System.out.println(annotation.name());            }        }    }}

输出结果

class java.lang.String     // 注解类型为字符串test                //如果不设置name属性,那么取默认值
0 0