美文网首页
java基础之自定义注解

java基础之自定义注解

作者: Let_Just_Do_it | 来源:发表于2020-09-08 09:14 被阅读0次

    自定义注解

    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyAnnotation {
    int id() default 0;

    String name() default ;
    

    }

    使用注解:

    package com.ck.wyy.basic.Annotation;
    import java.lang.reflect.Field;

    public class TestAnnotation{
    public static void main(String[] args) throws ClassNotFoundException {
    Class<?> myAnnotation = Anno.class;
    Field[] declaredFields = myAnnotation.getDeclaredFields();

        for (Field declaredField : declaredFields) {
            System.out.println(declaredField.getAnnotation(MyAnnotation.class).id());
        }
    }
    

    }

    class Anno {
    @MyAnnotation(id = 3)
    public int id;
    }

    返回结果:

    ''
    3

    Process finished with exit code 0
    ''

    注解的本质是反射

    相关文章

      网友评论

          本文标题:java基础之自定义注解

          本文链接:https://www.haomeiwen.com/subject/fahjsktx.html