注解用来给类声明附加额外信息,可以标注在类、字段、方法等上面,编译器、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));
}
}
}
}

最新文章

  1. CocoaPods第三方库管理 iOS
  2. 微信App支付通知验签
  3. [问题2014S11] 解答
  4. MyEclipse使用总结——MyEclipse去除网上复制下来的来代码带有的行号
  5. 【翻译】Kinect v2程序设计(C++-) AudioBeam篇
  6. XML文件操作类--创建XML文件
  7. Linux网络编程8——对TCP与UDP的简易封装
  8. 使用CATransition实现页面的“从左向右” “从右向左”的动画
  9. 常用的 Internet Browser adds-on/浏览器插件
  10. Windows使用Apache2配置Git服务器
  11. html浏览器兼容性 JavaScript语法
  12. mariadb cache
  13. 使用 python 操作 mongodb 常用的操作
  14. Tomcat优化之容易集合经验
  15. .Net(C#)用正则表达式清除HTML标签(包括script和style),保留纯本文(UEdit中编写的内容上传到数据库)
  16. Opencv undefined reference to `cv::imread() Ubuntu编译
  17. PHP 中解析 url 并得到 url 参数
  18. Get package name
  19. 【Java】关于MyBatis框架的总结
  20. Dockerfile 指令汇总及解析

热门文章

  1. 尝试解决 : Microsoft Visual C++ 14.0 is required 的问题
  2. dp--区间dp P1880 [NOI1995]石子合并
  3. JavaScript 2019.3.15
  4. Codeforces Round #622 (Div. 2)C2 Skyscrapers最大"尖"性矩形,思维||分治
  5. java-简单工程模板
  6. javaweb03 javaservlet基础一
  7. 编译seastar
  8. luogu P3835 【模板】可持久化平衡树
  9. for-each用法误区(不能改变数组元素值)
  10. php 去除中间空格