Java 之 自定义注解@interface

1.关键字:@interface

2.用法:

  a.自定义类注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)   //类注解
public @interface TypeAnnotation {

    String value();

}

 

  b.自定义字段注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)  //字段注解
public @interface FiledAnnotation {

    String value();
    String name();

}

 

  c.自定义方法注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //方法注解
public @interface MethodAnnotation {

    String value() default "index";
    String url() default "/";

}

 

  d.使用

    1)创建实体类,加上自义定注解

@TypeAnnotation(value = "testBean")
public class TestBean {

    @FiledAnnotation(value = "field", name = "中文名称")
    private String field;

    @MethodAnnotation() //不赋值则使用默认值
    public String getField() {
        return field;
    }

    @MethodAnnotation(value = "setField", url = "/setField")
    public void setField(String field) {
        this.field = field;
    }
}

 

    2)获取各注解参数值

    public static <T> void testAnnotation(T t){
        Class clazz = t.getClass();
        //获取类注解
        if(clazz.isAnnotationPresent(TypeAnnotation.class)){    //判断是否有注解
            TypeAnnotation typeAnno = (TypeAnnotation) clazz.getAnnotation(TypeAnnotation.class);
            System.out.println("[TypeAnnotation]: value[" + typeAnno.value() + "]");
        }
        //获取字段注解
        for(Field field : clazz.getDeclaredFields()){
            FiledAnnotation filedAnno = field.getAnnotation(FiledAnnotation.class);
            if(filedAnno != null){
                System.out.println("[FiledAnnotation]: value[" + filedAnno.value() + "], name[" + filedAnno.name() + "]");
            }
        }
        //获取方法注解
        for(Method method : clazz.getMethods()){
            MethodAnnotation methodAnno = method.getAnnotation(MethodAnnotation.class);
            if(methodAnno != null){
                System.out.println("[MethodAnnotation]: value[" + methodAnno.value() + "], url[" + methodAnno.url() + "]");
            }
        }
    }

    public static void main(String[] args) {
        testAnnotation(new TestBean());
    }

 

 

3.其他相关注解

  a.@Target注解:指定程序元定义的注释所使用的地方

    1)ElementType.TYPE:类型适用 class, interface, enum

    2)ElementType.FIELD:类型适用 field

    3)ElementType.METHOD:类型适用 method

    4)ElementType.PARAMETER:类型适用 method 的 parameter

    5)ElementType.CONSTRUCTOR:类型适用 constructor

    6)ElementType.LOCAL_VARIABLE:类型适用 局部变量

    7)ElementType.ANNOTATION_TYPE:类型适用 annotation 类型

    8)ElementType.PACKAGE:类型适用 package

 

  b.@Retention注解:这个元注释和java编译器处理注释的注释类型方式相关

    1)RetentionPolicy.SOURCE:编译器处理完Annotation后不存储在class中

    2)RetentionPolicy.CLASS:编译器把Annotation存储在class中,这是默认值

    3)RetentionPolicy.RUNTIME:编译器把Annotation存储在class中,可以由虚拟机读取,反射需要

 

posted @ 2019-10-24 15:53  晨M风  阅读(1067)  评论(0编辑  收藏  举报