Java Annotations Simple Learning

Source: Internet
Author: User

Annotations (also known as metadata) provide a formalized way for us to add information to our code, making it easy to use this data at a later time, to some extent, by combining the metadata with the source code files, rather than saving them in an external document.

annotations enable us to store additional information about the program in a format that will be tested and validated by the compiler in the future. Annotations can be used to generate descriptor files, even new class definitions, and to help alleviate the burden of writing "boilerplate" code. By using annotations, you save the metadata in the Java source code and use the annotation API to construct processing tools for annotations to read annotations.

Java currently contains only three standard annotations, as well as four types of meta annotations. Meta annotations are responsible for annotating other annotations. Most of the time, programmers define their own annotations and write their own annotation processors to handle them.

A simple example of annotations

Annotation definition:

1 Importjava.lang.annotation.*;2 3@Target (Elementtype.method)//define where annotations are used4@Retention (Retentionpolicy.runtime)//define the level at which annotations are available5  Public@InterfaceUseCase {6    Public intID ();7    PublicString description ()default"No description";8}

In annotations, some elements are typically included to represent certain values. These values are available to the program or tool when parsing the annotations. The annotated element looks like an interface method, and the only difference is that you can set a default value for it. Annotations with no elements become markup annotations.

Use annotations:

1 ImportJava.util.*;2 3  Public classPasswordutils {4@UseCase (id = Description = "Password must contain at least one numeric")5    Public BooleanValidatapassword (String password) {6     return(Password.matches ("\\w*\\d\\w*"));7   }8     9@UseCase (id = 48)Ten    Publicstring Encryptpassword (string password) { One     return NewStringBuilder (password). reverse (). toString (); A   } -      -@UseCase (id = $, Description = "New password can ' t equal previously used ones") the    Public BooleanCheckfornewpassword (list<string>prevpasswords, String password) { -     return!prevpasswords.contains (password); -   } -}

Annotations @UseCase can work with any modifier on a method, such as public,static , or void. From a grammatical point of view, annotations are used almost exactly the same way as modifiers. Annotations are defined much like the definition of an interface , and annotations, like any other Java interface, are compiled into class files.

Write the annotation Processor:

1 Importjava.lang.reflect.*;2 ImportJava.util.*;3 4  Public classUsecasetracker {5    Public Static voidTrackusecases (list<integer> usecases, class<?>cl) {6      for(Method m:cl.getdeclaredmethods ()) {7UseCase UC = M.getannotation (usecase.class);8       if(UC! =NULL) {9SYSTEM.OUT.PRINTLN ("Found use case:" + uc.id () + "" +uc.description ());TenUsecases.remove (NewInteger (Uc.id ()));  One       } A     } -      for(inti:usecases) { -SYSTEM.OUT.PRINTLN ("warning:missing use case-" +i); the     } -   } -    Public Static voidMain (string[] args) { -List<integer> usecases =NewArraylist<integer>(); +Collections.addall (Usecases, 47, 48, 49, 50); -Trackusecases (usecases, Passwordutils.class); +   }     A}

If there is no tool to read annotations, the annotations are not more useful than annotations. An important part of the process of using annotations is creating and using a note processor. Java SE5 extends the API of the reflection mechanism to help programmers construct such tools. It also provides an external tool apt to help programmers parse the Java Source code with annotations.

Types of annotation elements:

· All basic types (int, float, boolean , etc.)

· String

· Class

· enum

· Annotation

· Arrays of the above types

If other types are used, the compiler will make an error. Annotations can also be types of elements, that is, annotations can be nested .

Reference: "Java Programming Ideas"

Java Annotations Simple Learning

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.