关于Java中注解的总结

  注解用来给类声明附加额外信息,可以标注在类、字段、方法等上面,编译器、JVM以及开发人员等都可以通过反射拿到注解信息,进而做一些相关处理

  • Java中注解的知识结构图

  • 常用注解

  @Override     只能标注在子类覆盖父类的方法上面,有提示的作用

  @Deprecated    标注在过时的方法或类上面,有提示的作用

  @SuppressWarnings("unchecked")   标注在编译器认为有问题的类、方法等上面,用来取消编译器的警告提示,警告类型有serial、unchecked、unused、all

  • 元注解

  元注解用来在声明新注解时指定新注解的一些特性

  @Target 指定新注解标注的位置,比如类、字段、方法等,取值有ElementType.Method等

  @Retention 指定新注解的信息保留到什么时候,取值有RetentionPolicy.RUNTIME等

  @Inherited  指定新注解标注在父类上时可被子类继承

  • 声明注解
@Target(ElementType.METHOD) // 指定新注解可以标注在方法上
@Retention(RetentionPolicy.RUNTIME) // 指定新注解保留到程序运行时期
@Inherited // 指定新注解标注在父类上时可被子类继承
public @interface DisplayName {
    public String name();
}
  • 使用注解
public class Person {
    private String name;
    private int age;

    @DisplayName(name = "姓名")
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @DisplayName(name = "年龄")
    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
  • 获取注解信息
public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setName("蛋蛋");
        person.setAge(16);

        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
        PropertyDescriptor[] propDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propDescriptor : propDescriptors) {
            Method getMethod = propDescriptor.getReadMethod();
            if (getMethod != null && !"class".equalsIgnoreCase(propDescriptor.getName())) {
                DisplayName displayName = getMethod.getAnnotation(DisplayName.class);
                if (displayName != null) {
                    System.out.println(displayName.name() + ":" + getMethod.invoke(person));
                } else {
                    System.out.println(propDescriptor.getName() + ":" + getMethod.invoke(person));
                }
            }
        }
    }

 

posted on 2019-01-31 14:31  朱*力  阅读(439)  评论(0编辑  收藏  举报

导航