Explanation of "interview plus sub-item" Java Custom annotations

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.