The use of Java annotations

chenweicool 2020-11-11 17:58:02
use java annotations


java The use of annotations in

1. Let's go back to the front

The benefits of annotation development

1. Make the code cleaner and easier to read , Easy to maintain and modify . such as , I used to use spring Development of , It's all based on xml The file realizes unified configuration management , But the disadvantages are also obvious , As the project gets bigger and bigger ,xml The files will get more and more complicated , Maintenance costs will also be higher and higher . Using annotations can provide greater convenience , Easy to maintain and modify .

2 Can implement code type checking , Especially in the compiler's point of view to achieve some type checking , For example, pre inspection (@Override) And suppress warnings (@SuppressWarnings) etc. .

3 Custom annotation , As a carrier of additional information , Store additional information about the program

2 Classification and use of annotations

​ Java Annotations are bits of meta-information attached to code , For compiling and runtime parsing and using , Play a show 、 Configured functionality .

Annotations don't affect the actual logic of the code , Play a supporting role only . Included in java.lang.annotation In bag . The definition of annotations is similar to the definition of interfaces , Use @interface To define , Defining a method defines an element for the annotation type , Method declaration does not allow parameters or throw sentence , The return value type is limited to the original data type 、 character string String、Class、enums、 Annotation type , Or the array of the previous ones , Methods can have default values . Annotations don't directly affect the semantics of the code , But it can be seen as a program tool or class library . It, in turn, has an impact on the semantics of the running program . Annotations can be from source files 、class The file can be read by reflection mechanism at runtime .

Generally speaking , There are three types of annotations : Yuan notes , Standard notes , Custom annotation

2.1 Yuan notes

Meta annotation is responsible for annotating other annotations , It mainly indicates the scope of use of the annotation , Effective range . We can't change it , It can only be used to define our own annotations .

Include @Retention @Target @Document @Inherited Four kinds of .(java.lang.annotation Provided in the , For annotation type ).

annotation explain
@Target Define the purpose of the annotation , In other words, annotations can be defined to act on classes , On the way , Or variables
@Retention Define retention policies for annotations .RetentionPolicy.SOURCE: Annotations only exist in source code , stay class The bytecode file does not contain ;RetentionPolicy.CLASS: Default retention policy , Annotations will be in class Bytecode file exists , But the runtime can't get ;RetentionPolicy.RUNTIME: Annotations will be in class Bytecode file exists , At run time, you can get... By reflection .
@Document Indicate that the annotation will be included in javadoc in
@Inherited Indicates that the subclass can inherit the annotation in the parent class

Target Type mainly depends on ElementType This type , The specific types are as follows :

Target type explain
ElementType.TYPE Interface 、 class 、 enumeration 、 annotation
ElementType.FIELD Field 、 Enumerated constant
ElementType.METHOD Method
ElementType.PARAMETER Method parameter
ElementType.CONSTRUCTOR Constructors
ElementType.LOCAL_VARIABLE local variable
ElementType.ANNOTATION_TYPE annotation
ElementType.PACKAGE package

2.2 Standard notes

Java The standard notes provide three , It's defined in java.lang The annotations in , I think these three annotations are more of a kind of annotation

  • @Override Indicates that the method in the parent class is overridden by the current method .

  • @Deprecated Mark an element as expired , Avoid using

The supported element types are :CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE

  • @SuppressWarnings The compiled output does not correspond to

    A simple use demo:

    @SuppressWarnings(value = {"unused", "rawtypes"})
    public class Children extends Parent{
    @Override
    public void work() {
    System.out.println(" I'm a rewritten method ");
    }
    @Deprecated
    public void play(){
    System.out.println(" This method is not recommended ");
    }
    }
    

2.3 Custom annotations implement a sql Statement splicing

What needs attention : The definition of annotations is similar to the definition of interfaces , Use @interface To define , Defining a method defines an element for the annotation type , Method declaration does not allow parameters or throw sentence , The return value type is limited to the original data type 、 character string String、Class、enums、 Annotation type , Or the array of the previous ones , Methods can have default values .

Custom annotations can be divided into three steps : Definition notes , Using annotations , Read annotation

Definition notes

@Target(ElementType.TYPE) // Annotation loading class
@Retention(RetentionPolicy.RUNTIME) // Read annotations at run time
public @interface Table {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
[email protected] UserFiled {
String name();
String type();
int length();
}

Using annotations

// Add custom annotations to the user , Implement a table mapping
@Table(value = "user_table")
public class User {
@UserFiled(name = "user_id",type = "int",length = 8)
private int userId;
@UserFiled(name = "user_name",type = "varchar",length = 16)
private String userName;
@UserFiled(name = "password",type = "varchar",length = 16)
private String password;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Read the content of the annotation

/**
* Read the value in the annotation
*/
public class GetUser {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class userClass = Class.forName("annocation.blog.User");
// Read the annotations on the class
Table table = (Table) userClass.getAnnotation(Table.class);
System.out.println(table.value());
// Read comments on attributes
Field userId = userClass.getDeclaredField("userId");
UserFiled userFiledId = userId.getAnnotation(UserFiled.class);
System.out.println(userFiledId.length() + "----" + userFiledId.type() + "-----" + userFiledId.name());
Field userName = userClass.getDeclaredField("userName");
UserFiled userFiledName = userName.getAnnotation(UserFiled.class);
System.out.println(userFiledName.length()+"----"+userFiledName.type()+"----"+userFiledName.name());
Field password = userClass.getDeclaredField("password");
UserFiled userFiledPassword = password.getAnnotation(UserFiled.class);
System.out.println(userFiledPassword.name() + "-----" + userFiledPassword.type() + "-----" + userFiledPassword.length());
// Splice one sql sentence
String name = "chenwei";
String sql ="select * from" + table.value()+"where"+userFiledName.name()+"="+name;
}
}

result :

user_table
user_id----int-----8
user_name----varchar----16
password-----varchar-----16

The implementation process of custom annotation :

1, Definition notes

2, Using annotations , Use your own defined annotations to achieve some purpose , In this case , Annotation is used to complete the mapping relationship between database table and entity class

3 Read the content of the annotation , It's also an important part , The core still uses the idea of reflection , Get the class that uses annotations , According to the class getAnnotion Method to get the definition of annotation , Get the value on the annotation .

3 The principle of annotation implementation

A large part of the principle of annotation implementation is based on reflection implementation .

​ Reflection can get Class object , And then get Constructor、Field、Method Etc , Click open source structure to find Class、Constructor、Field、Method And so on AnnotatedElement Interface ,AnnotatedElement The interface method is as follows

// Determines whether the element contains the specified annotation , Include returns true
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
// Returns the corresponding annotation on the element , If there is no return null
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
// Returns all annotations on the element , If there are no annotations, an empty array is returned
Annotation[] getAnnotations();
// Returns the specified type of annotation , If it doesn't return an empty array
T[] getAnnotationsByType(Class<T> annotationClass)
// Returns the specified type of annotation , If it doesn't return an empty array , Only annotations with direct annotation , It doesn't contain inherited Annotations
T getDeclaredAnnotation(Class<T> annotationClass)
// Returns the specified type of annotation , If it doesn't return an empty array , Only annotations with direct annotation , It doesn't contain inherited Annotations
T[] getDeclaredAnnotationsByType
// Returns all annotations on the element , If there are no annotations, an empty array is returned , Only annotations with direct annotation , It doesn't contain inherited Annotations
Annotation[] getDeclaredAnnotations();

Through an example to illustrate the use of annotations again :

Definition notes

@Documented
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotaion {
String getValue() default "this is myAnntaion";
int order() default 0;
}

Using annotations

@MyAnnotaion(getValue = "annotation on class")
public class Demo {
@MyAnnotaion(getValue = "annotation on filed")
public String name;
@MyAnnotaion(getValue = "annotation on method")
public void hello(){
}
@MyAnnotaion
public void defaultMethod(){
}
}

Using reflection to read values in annotations .

public class TestDemo {
public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
/**
* Gets the annotations on the class
*/
Class<Demo> demoClass = Demo.class;
Annotation[] annotaion = demoClass.getAnnotations();
printAnnotation(annotaion);
/**
* Read comments on member variables
*/
Field name = demoClass.getField("name");
Annotation[] getOnFiled = name.getAnnotations();
printAnnotation(getOnFiled);
/**
* Read the annotation on the method
*/
Method hello = demoClass.getMethod("hello", null);
MyAnnotaion onMethod = hello.getAnnotation(MyAnnotaion.class);
System.out.println(onMethod.getValue());
/**
* Get annotations on the default method
*/
Method defaultMethod = demoClass.getMethod("defaultMethod", null);
MyAnnotaion onDefaultMethod = defaultMethod.getAnnotation(MyAnnotaion.class);
System.out.println(onDefaultMethod.getValue());
}
public static void printAnnotation(Annotation... annotations) {
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
}
}

Running results

@annocation.MyAnnotaion(getValue=annotation on class, order=0)
@annocation.MyAnnotaion(getValue=annotation on filed, order=0)
annotation on method
this is myAnntaion

Reference material :

http://blog.kimzing.com/java/Java From introduction to mastery - It's enough to learn this one /

《java Programming idea 》

版权声明
本文为[chenweicool]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云