Java: annotation (metadata), java annotation metadata

Source: Internet
Author: User
Tags modifiers

Java: annotation (metadata), java annotation metadata

Java Annotation

The so-called Metadata refers to the data used to describe the data. You may be a little unfamiliar when you hear the metadata, in fact, any developer who has used struts or hibernate uses metadata without knowing it. More broadly, Metadata refers to describing the relationship between code or code and other resources (such as database tables) the internal relationship between data, for Struts is the struts-config.xml file, for hibernate is. hbm file. However, existing metadata files that exist in xml or other ways have some inconvenience (for example, separation from the described files is not conducive to consistent maintenance ).

JDK1.5 introduces the concept of Annotation to describe metadata based on metadata, which provides us with a method to add information in code, this allows us to easily use the data at runtime or at a certain time point (using the data through parsing annotations)


Function of Annotation

A. Compile the document: generate the document through the metadata identified in the Code. Commonly Used documents include @ param and @ return ;.

B. Code Analysis: analyze the Code through the metadata identified in the code.

(1) Replace. properties and xml configuration files: Annotations can be used as part of the configuration information for software deployment, providing a simple and easy to understand way. However, annotations are not suitable when the configuration information needs to be dynamically changed at runtime. Annotation-based configuration starting from spring 2.5 is commonly used to reduce configuration files. Currently, the framework uses this configuration to reduce the number of configuration files.

(2) Support for cross-cutting concerns: Annotations can well handle dependency injection, service discovery and management objects, verification, and many other similar things. If you need to use Aspect-Oriented Programming, and you do not want to use another aspect-oriented language (such as AspectJ), annotation is a feasible option.

C. Compile check: Use the metadata identified in the code to enable the compiler to perform basic compilation check.


Java built-in annotation set

Annotations can be used for program elements such as classes, methods, variables, parameters, and packages. Java defines a built-in annotation set:

(1) annotations for Java code:

@ Override: The verification method is a rewrite method. If the method is not found in the parent class, a compilation warning is generated.

@ Deprecated: the flag method is obsolete. If this method is still used, a compilation warning is generated.

@ SuppressWarnings: notifies the compiler to suppress the compile-time warnings specified by annotation parameters.

(2) For other annotations: The Meta annotations described below share a common feature that they can only be used in the Annotation statement.

@ Retention: it is used to declare the Retention policy of the annotation, that is, the life range. There are three types of Annotations: CLASS, RUNTIME, and SOURCE, which respectively indicate that the annotation is saved in the CLASS file, jvm runtime, and SOURCE code. Only when declared as RUNTIME canReflection APITo obtain the annotation information. If the annotation declaration does not contain the Retention annotation, the default Retention policy isRetentionPolicy. CLASS.

@ Target: indicates the type of the program element to which the annotation applies, that is, the scope of the annotation (such as methods and fields). If the annotation declaration does not contain the Target, the declared annotation can be used on any program element.

@ Brief ented: indicates that a type of annotation will be Documented using javadoc and similar default tools.

@ Inherited: it can only be used for Class-level Annotation. It indicates that the marked Annotation will be automatically Inherited by all sub-classes of the Class.


Custom Annotation

Java allows custom annotations, which are defined by @ interface before the class name. Java. lang. annotation contains the meta annotations and interfaces required for all custom annotations, such as the java interface. lang. annotation. annotation is an interface inherited by all annotations and is automatically inherited. It is specified when no definition is required. It is similar to that where all classes automatically inherit objects.


package com.test;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)public @interface MyAnnotation {        public String name();        public int value() default 0;}

Note: In the above example, each method actually declares a configuration parameter. The parameter name is the method name, the parameter type is the return value type of the method (the return value type can only be basic type, Class, String, or enum). You can use default to declare the default value of the parameter.


Java annotations

After a preliminary understanding of Java annotations, I will elaborate on some parameters here

(1) @ Target indicates the scope of the annotation. The optional parameter values include:

ElemenetType. CONSTRUCTOR ----------------------------- the CONSTRUCTOR declares ElemenetType. FIELD -------------------------------------- FIELD Declaration (including enum instances) ElemenetType. LOCAL_VARIABLE -------------------------- ElemenetType is declared as a local variable. METHOD ---------------------------------- METHOD declaration ElemenetType. PACKAGE --------------------------------- PACKAGE declaration ElemenetType. PARAMETER -------------------------------- PARAMETER declaration ElemenetType. TYPE --------------------------------------- class, interface (including annotation TYPE), or enum Declaration

(2) @ Retention indicates the level at which the annotation information is saved. The optional parameter values include:

RetentionPolicy. SOURCE ----------------------------------- the annotation will be discarded by the compiler RetentionPolicy. CLASS ----------------------------------- the annotation is available in the class file, but the RetentionPolicy will be discarded by the VM. RUNTIME ------------------------------- the VM retains the annotation at RUNTIME, so the annotation information can be read through the reflection mechanism.


Annotation Processor

Annotations added to a program can be processed by the annotation processor at compilation or runtime. The essence of the annotation processor is to be processed through Java reflection.


Application: customize an annotation and parse the annotation using Java reflection

The following is a cool case on the Internet:

Annotation definition:

Package com. annotation. test; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/*** contact information verification */@ Retention (RetentionPolicy. RUNTIME) @ Target (ElementType. FIELD) @ brief ented public @ interface ContactValidator {public ContactType type ();}

Contact information enumeration:

Package com. annotation. test;/*** contact type */public enum ContactType {EMAIL, PHONE, MOBILE, WEBSITE}


Package com. annotation. test; public class User {/*** name */private String name;/*** mailbox */
@ ContactValidator (type = ContactType. EMAIL)
Private String email;/*** phone number */
@ ContactValidator (type = ContactType. PHONE)
Private String phone;/*** mobile phone number */
@ ContactValidator (type = ContactType. MOBILE)
Private String mobile;/*** URL */
@ ContactValidator (type = ContactType. WEBSITE)
Private String website; public String getName () {return name;} public void setName (String name) {this. name = name;} public String getEmail () {return email;} public void setEmail (String email) {this. email = email;} public String getPhone () {return phone;} public void setPhone (String phone) {this. phone = phone;} public String getMobile () {return mobile;} public void setMobile (String mobile) {this. mobile = mobile;} public String getWebsite () {return website;} public void setWebsite (String website) {this. website = website ;}}

Verification tool:

Package com. annotation. test; import java. util. regex. matcher; import java. util. regex. pattern; public class ValidatorUtil {/*** check email ** @ param email * @ return */public static boolean isValidEmail (String email) {Pattern p = Pattern. compile (". + @. + \\. [a-z] + "); Matcher m = p. matcher (email); return m. matches ();}/*** verification phone ** @ param phone * @ return */public static boolean isValidPhone (String phone ){ Pattern p = Pattern. compile ("\ d ([, \ s])? \ D ([, \ s])? \ D "); Matcher m = p. matcher (phone); return m. matches ();}/*** verify the mobile phone number ** @ param mobile * @ return */public static boolean isValidMobile (String mobile) {Pattern p = Pattern. compile ("^ [1] ([3] [0-9] {1} | 59 | 58 | 88 | 89) [0-9] {8} $ "); matcher m = p. matcher (mobile); return m. matches ();}/*** verify the URL ** @ param website * @ return */public static boolean isValidWebsite (String website) {Pattern p = Pattern. Compile ("^ (https? | Ftp | file): //. + $ "); Matcher m = p. matcher (website); return m. matches ();}}


Package com. annotation. test; import java. lang. annotation. annotation; import java. lang. reflect. field; import java. lang. reflect. modifier; public class FieldAnnotationParser {/*** parser * @ param user * @ throws IllegalArgumentException * @ throws IllegalAccessException */public static void parser (User user) throws producer, illegalAccessException {// obtain all fields [] fields = user. getClass (). GetDeclaredFields (); for (Field field: fields) {Annotation [] annotations = field. getAnnotations (); // obtain all the annotations on the field for (Annotation annotation: annotations) {// if it is annotation Annotation if (annotation instanceof ContactValidator) {ContactValidator = (contactValidator) annotation; if (field. getModifiers () = Modifier. PRIVATE) {// if it is a PRIVATE field, set the reflected object to cancel the Java language access check field during use. setAccessible (true);} boo Lean result = false; // ID variable // obtain the field value String fieldValue = (String) field. get (user); switch (contactValidator. type () {case EMAIL: result = ValidatorUtil. isValidEmail (fieldValue); break; case PHONE: result = ValidatorUtil. isValidPhone (fieldValue); break; case MOBILE: result = ValidatorUtil. isValidMobile (fieldValue); break; case WEBSITE: result = ValidatorUtil. isValidWebsite (fieldValue); break;} if (! Result) {System. out. println ("Invalid" + field. getName () + ":" + fieldValue );}}}}}}

Test class:

Package com. annotation. test; public class AnnotationTest {/*** main function * @ param args * @ throws IllegalAccessException * @ throws IllegalArgumentException */public static void main (String [] args) throws limit, illegalAccessException {User user = new User (); user. setName ("TimSturt"); user. setPhone ("0931234 3819"); // incorrect phone format user. setMobile ("13575309630"); // The correct mobile phone format is user. setEmail (""); // The correct email format is user. setWebsite ("fttp: //"); // The website url is FieldAnnotationParser. parser (user );}}

The output is as follows:

Invalid phone: 0931234 3819Invalid website: fttp://

Explanation: regular expressions in the validation tool class are not applicable to all situations and can be adjusted by yourself.



In Java, metadata is stored as tags in Java code. The existence of metadata tags does not affect compilation and execution of program code, it is only used to generate other files or to know the description of the Code to be run at runtime.

Briefly describe the aforementioned content:

1. Metadata is stored in Java code as tags.
Second, the metadata description information is type-safe, that is, the fields inside the metadata are clearly typed.
Third, metadata requires additional processing by tools outside the compiler to generate other program components.
4. metadata can only exist at the Java source code level or within the compiled Class file.

Key points:

(1)Annotation Syntax:

modifiers @interface AnnotationName{    element declaration1    element declaration2    . . .}

Modifiers indicates public, protected, private, or default value (nothing ).


(2)Element declaration ):

Type elementName ();
Type elementName () default value;


(3)You can use Annotation as follows:

@ AnnotationName (elementName1 = value1, elementName2 = value2,...). The order of element declarations is irrelevant. Elements with default values can be excluded from the initialization table. In this case, they use the default values.

  A,According to the above description, the three Annotation defined below are equivalent:
@ BugReport (assignedTo = "Harry", severity = 0)
@ BugReport (severity = 0, assignedTo = "Harry ")
@ BugReport (assignedTo = "Harry ")

  B,If there is only one element, it is best to set the parameter name to value. When assigning a value, you do not need to specify a name and assign a value directly, as shown below:
AnnotationName ("somevalue ")

  C,If the Annotation element is an array, you can make the following declaration:
@ BugReport (..., reportedBy = {"Harry", "Carl "})

  D,If there is only one element in the array, you can make the following declaration:
@ BugReport (..., reportedBy = "Joe") // OK, same as {"Joe "}

  E,If the Annotation element type is Annotation, you can make the following declaration:
@ BugReport (testCase = @ TestCase (name = "free "),...)


 (4)The element types in Annotation must be the following or a combination of these types (arrays of the following types ):

Basic Types (int, short, long, byte, char, double, float, boolean), String (String), Class, enumeration type (enum), Annotation type

Related Article

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: 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.