[JAVA Basics] annotation, java Annotation

Source: Internet
Author: User

[JAVA Basics] annotation, java Annotation

For the following content, refer to java programming ideology-4. The jdk version is jdk5.0, which is somewhat old-_-|

What is annotation?

The introduction of JAVA SE5, also known as metadata, can be directly added to the Code to fully describe the information required by the program, which cannot be expressed in Java;

Built-in Annotation

JDK has three built-in standard annotations and four meta annotations;

Three standard annotations are defined in java. lang:

@ Override // indicates that the subclass method overwrites the parent class method.

@ Deprecated // The API is out of date and is not recommended

@ SuppressWarnings // cancel the compiler warning

Four meta Annotations:

@ Target // specify where the annotation can be used

Optional parameters:

CONSTRUCTOR: CONSTRUCTOR Declaration

FIELD: domain Declaration

LOCAL_VARIABLE: local variable Declaration

METHOD: METHOD declaration

PACKAGE: PACKAGE Declaration

PARAMETER: PARAMETER Declaration

TYPE: class and interface declaration

@ Retention // indicates the level at which the annotation is available

Optional parameters:

SOURCE: annotation will be discarded by the compiler;

CLASS: The annotation is available in the class file, but will be discarded by the VM;

RUNTIME: the VM retains the annotation during running, and the annotation information can be read through the reflection mechanism;

@ Incluented // indicates that the annotation is included in Javadoc.

@ Inherited // allow subclass to inherit the annotation of the parent class

Basic syntax custom Annotation

Tag Annotation

Define a @ Test annotation, as shown in the following code. The annotation definition is similar to the interface. In fact, the annotation is also compiled into a class file like the interface;

package annotations;import java.lang.annotation.*;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Test {    }

In annotations, some elements are usually contained to indicate some values. When analyzing and processing annotations, the program can read these values;

The above @ Test annotation does not contain elements, which are called Tag annotation;

Annotation containing elements

The following code defines an annotation containing elements. The definition of an element is similar to a method. The definition contains the data type of the element. For example, id is int type and description is String type, it also contains a default value;

package annotations;import java.lang.annotation.*;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface UseCase {    public int id();    public String description() default "no description";}

Note: The available types of annotation elements are as follows:

All basic data types (int, double ...)

String

Class

Enum

Annotation

Array (the above type is element)

If other types of compilers are used, an error is reported. A special reminder is that the packaging types of Integer, Double, and other basic data types are not allowed;

In addition, elements cannot have uncertain values, either have default values, or provide element values, and cannot be null;

Annotation usage

The usage of the @ UseCase annotation defined above is as follows. It is very simple. Write the annotation before the method and specify the value of the element. If not specified, the default value is used;

package annotations;import java.util.*;public class PasswordUtils {    @UseCase(id = 47, description = "Passwords must contain at least one numeric")    public boolean validatePassword(String password) {        return (password.matches("\\w*\\d\\w*"));    }    @UseCase(id = 48)    public String encryptPassword(String password) {        return new StringBuilder(password).reverse().toString();    }    @UseCase(id = 49, description = "New passwords can't equal previously used ones")    public boolean checkForNewPassword(List<String> prevPasswords, String password) {        return !prevPasswords.contains(password);    }} 
Annotation processing tool

Using the reflection mechanism of JAVA, you can find annotation tags. The following is a simple annotation processor used to parse the @ UserCase annotation mentioned above. It mainly uses getDeclaredMethods () of the Class () the getAnnotation (Class <T> annotationClass) Method of the Method Class; getDeclaredMethods returns all the methods declared in the Class, and getAnnotation returns the specified annotation;

package annotations;import java.lang.reflect.*;import java.util.*;public class UseCaseTracker {    public static void trackUseCases(List<Integer> useCases, Class<?> cl) {        for (Method m : cl.getDeclaredMethods()) {            UseCase uc = m.getAnnotation(UseCase.class);            if (uc != null) {                System.out.println("Found Use Case:" + uc.id() + " "                        + uc.description());                useCases.remove(new Integer(uc.id()));            }        }        for (int i : useCases) {            System.out.println("Warning: Missing use case-" + i);        }    }    public static void main(String[] args) {        List<Integer> useCases = new ArrayList<Integer>();        Collections.addAll(useCases, 47, 48, 49, 50);        trackUseCases(useCases, PasswordUtils.class);    }}
Annotation Common Use Cases

Describes the ing between database table structures and class relationships (hibernate ...)

Unit Test (junit ...)

Some configurations (spring ...)

...

 

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.