My previous blog has described the declaration of custom annotations Today we look at how we can use the annotations we define ourselves.
1. We use our annotations in the program.
In the previous article we customized an annotation:
@Target(ElementType.FIELD)//注解的作用范围,就是注解是用在什么地方的@Retention(RetentionPolicy.RUNTIME)//注解的级别,就是注解能留存到什么时候@Documented@Inheritedpublic @interface MyAnnotation { publicvalue();//注解可以接收的参数}
This annotation has only one parameter, so we do not need to display the description parameter name when we use it. Let's write a class and use annotations.
publicclass People { @MyAnnotation("liu") private String name; publicPeople() { Inject.injectfeild(this); } publicgetName(){ return name; }}
You can see that we wrote a class and wrote a note on top of him, assuming that the function we are now implementing is to assign the value in the annotation to the following property name, what should we do? Here we can see that we have called inject.injectfeild (this) in the constructor method, which is how we parse the annotations, and then we'll look at how it's done.
2. Parsing the annotations
No more nonsense. First, the code:
Public class Inject { Public Static void Injectfeild(Object o) {class<?> clazz = O.getclass ();//Get the class passed infield[] fields = Clazz.getdeclaredfields ();//Get the domain of the class by reflection (global variable) for(Field field:fields) {//See if this field has our own custom annotation class flags. if(Field.isannotationpresent (Myannotation.class)) {Myannotation inject = field.getannotation (Myannotation.class);//Get to our annotationsString Value=inject.value ();//Get parameters for annotationsField.setaccessible (true);Try{Field.set (o, value);//Assign values to our fields}Catch(IllegalArgumentException | Illegalaccessexception e) {e.printstacktrace (); } } } }}
In fact, we get the value of the annotation and the corresponding field by reflection, and we assign the value to him. Let's take a look at the test again:
publicclass Test { publicstaticvoidmain(String[] args) { People people=new People(); System.out.println(people.getName()); }}
Results:
Liu
Of course, normally a field assignment for an ordinary class can be given directly to a set function, which is just an example of how to make a custom annotation. However, in many frameworks their properties are assigned in this way, because it is interesting to learn about the IOC in order to understand the decoupling.
Because upload to CSDN source audit has not passed, need source code can stay in the comments in the mailbox, I will send the past as soon as possible.
Copyright NOTICE: This article is the original blog article, reproduced please indicate the source
Explanation of "interview plus sub-item" Java Custom annotations