随笔 自定义注解简单实现

自定义注解: 

@Target(FIELD)
@Retention(RUNTIME)
@Documented
public @interface Ano {
    public String name() default "ycx";
    public String value();
}

@Documented // 代表这个注解,可以被javadoc 处理的(加不加都行)

@Retention(RetentionPolicy.RUNTIME)

// RetentionPolicy 生命周期,一共有三个

// SOURCE 只留在源码,编译好后的代码是不有该注解的,该注解一旦编译就不存在了 ;

// class 只停留在字节码,运行时不会有;

// RUNTIME 运行时需要反射来获取该注解

@Target({ElementType.TYPE,ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE, ElementType.PACKAGE, ElementType.ANNOTATION_TYPE})

// 该注解用在地方(方法,参数,类)

使用:

public class test2 {
    @Ano(value = "555")
    private String value1;

    public static void main(String[] args) {
        test2 m=new test2();
        m.method();
    }
    public void method() {
       Field[] fields = test2.class.getDeclaredFields();
       Ano a =  fields[0].getAnnotation(Ano.class);
        System.out.println(a.name()+","+a.value());
    }
}

 输出:

ycx,555

猜你喜欢

转载自blog.csdn.net/qq_39404258/article/details/106380065