Java annotation (Annotation) Introduction __java

Source: Internet
Author: User
Tags deprecated modifier reflection
first, the concept
annontationIs the new feature that JDK5.0 began to introduce. The Chinese name is generally called Annotations。 It provides a secure, annotation-like mechanism for associating any information or metadata (metadata) with program elements (classes, methods, member variables, and so on).
More generally, the elements of a program (classes, methods, member variables) are added to a more intuitive and straightforward description, which is irrelevant to the business logic of the program and is intended for use by the specified tool or framework.
Annontation, like a modifier, applies to packages, types, construction methods, methods, member variables, parameters, and declaration statements for local variables.


Second, the principle Annotation is actually an interface. Access to annotation information through the Java reflection mechanism-related APIs. A related class (a class in a frame or tool) determines how the program element is used or changes their behavior based on that information.
annotation does not affect the execution of program code, regardless of how annotation changes, the code is consistently executed. These annotation are ignored by the Java language interpreter at work, so these annotation are "non-functional" in the JVM, and can only be accessed and processed by supporting tools for these annotation types of information.

Similarities and differences between annotation and interface: 1, annotation type uses keyword @interface instead of interface.
This keyword declaration implicitly implies a message: it inherits the Java.lang.annotation.Annotation interface and does not declare a interface
2, the annotation type, the method definition is unique, is limited.
A method of a annotation type must be declared as having no arguments and no exceptions thrown. These methods define the members of the annotation: The method name becomes the member name, and the method return value becomes the type of the member. The method return value type must be a primitive type, class type, enumeration type, annotation type, or one-dimensional array of elements from one of the preceding types. Method can be used to declare the default value of a member by using default, and a defaults value, which cannot be used as a member default, which is very different from the way we define methods in a annotation type.
The annotation type and its methods cannot use annotation type parameters, members cannot be generic (generics). Only a method that returns a value type of class can use generic (generics) in a annotation type, because this method can convert various types to class using class conversions.
3, annotation type and interface has a similar place.
They can define constants, static member types (such as enumeration type definitions). Annotation types can also be implemented or inherited as interfaces.


third, applications in the development of Java programs, especially Java EE applications, always have to deal with a variety of configuration files. With the typical S (pring) s (truts) H (ibernate) architecture in Java EE, the three frameworks for Spring, struts, and hibernate have their own XML-formatted configuration files. These profiles need to be saved in sync with the Java source code, otherwise there may be an error. And these errors are likely to be discovered at run time. It's always a bad idea to keep the same information in two places. Ideally, it would be nice to maintain this information in one place. The information that is required in the other sections is generated by automatic means. The mechanism of the annotations (Annotation) in source code is introduced in JDK 5. Annotations enable the Java source code to include not only functional implementation code, but also meta data. Annotations function like annotations in code, but annotations are not a description of the functionality of the code, but rather an important part of implementing the program's functionality. Java annotations have been widely used in many frameworks to simplify configuration in programs .


iv. common standards of annotationJava currently consists of three standard annotations and four kinds of meta annotations.
Starting with the JDK5.0 version, three types ofStandard annotation Type
1,@Override
Java.lang.Override is a marker annotation type, which is used as a notation method. It demonstrates that the annotated method overloads the parent class and acts as an assertion. If we use this annotation in a method that does not overwrite the parent class method, the Java compiler will alert with a compilation error.
This annotaton often adds a supportability validation process when we try to overwrite the parent method and write the wrong method name.
2,@Deprecated
Deprecated is also a kind of marker annotation. When a type or a member of a type is decorated with @deprecated, the compiler will not encourage the use of this annotated program element. So using this modifier has a certain "continuity": if we use this obsolete type or member in the code by inheritance or overwrite, the compiler still has to call the police, although the inherited or overridden type or member is not declared as @Deprecated.
Note: @Deprecated This annotation type is different from the one in Javadoc @deprecated this tag: The former is recognized by the Java compiler, The latter is a description that is identified by the Javadoc tool to generate documents that include why the program member is obsolete, how it should be banned, or substituted.
3,@SuppressWarnings
This annotation tells the Java compiler to turn off warnings for classes, methods, and member variables.
Sometimes, when compiling a warning, there are hidden bugs, some unavoidable, and some warnings that you don't want to see, which can be masked by this annotation.
Suppresswarning is not a marker annotation. It has a member of type string[] whose value is a prohibited warning name. For the Javac compiler, a warning name that is valid for the-xlint option is also valid for @suppresswarings, while the compiler ignores the unrecognized warning name.


annotation refers to the modification of the annotation annotation. The following four kinds of meta annotation are defined in the JDK:

1,@Target: Specifies which member of the class the annotation is used to modify. The @Target contains a member variable named value with type ElementType. Specify the annotation usage scope through this variable

Type: Class, Interface, or enum (enum) declaration

Field: Field (property) declaration

Methods: Method declarations

PARAMETER: Parameter declaration

Constructor: Constructing method declarations

local_variable: local variable declaration

Annotation_type: annotation type declaration

PACKAGE: Package Declaration
2.@Retention: Can only be used to modify a Annotation definition that specifies the domain that the Annotation can retain, @Rentention contains a member variable of a retentionpolicy type, which is defined by the variable Fixed field.
Retentionpolicy.class: The compiler will record the annotations in the CLASS file. When you run a Java program, the JVM does not retain annotations. This is the default value
Retentionpolicy.runtime: The compiler will record the annotations in the class file. When you run a Java program, the JVM retains annotations. The program can get the comment through reflection
Retentionpolicy.source: Compiler discards comments for this policy directly
3.@Documented: The Annotation class that is used to specify that the Annotation is decorated by this element will be extracted from the Javadoc tool as a document.

4.@Inherited: The Annotation modified by it will be inherited. If a class uses a Annotation that is @Inherited decorated, its subclasses automatically have that annotation.


v. Use of standard annotations

Suppresswarnings is a more commonly used annotation that we use as follows:

@SuppressWarnings ("unchecked") public
	void aaa () {
		
	}


We can view the source code of the standard annotation suppresswarnings in JDK:

@Target ({TYPE, FIELD, method, PARAMETER, constructor, local_variable})
@Retention (Retentionpolicy.source)
Public @interface suppresswarnings {
    /** * The set of warnings, are to is suppressed by the
     compiler in THE
  * annotated element.  Duplicate names are permitted.  The second and
     * Successive occurrences of a name are ignored.  The presence of
     * Unrecognized warning names is <i>not</i> a error:compilers must
     * Ignore any warn ing names they does not recognize.  They are, however,
     * free to emit a warning if is annotation contains an unrecognized
     * warning name.
     *
     * <p>compiler vendors should document the warning names they support in
     * conjunction with this Annotati On type. They are encouraged to cooperate * to ensure, the same names, work, across multiple
     .
     *
    /string[] Value ();
}

You can see that the suppresswarnings annotation type only defines a single member value, so there is only one simple value={...} As Name=value pairs. Also, because the member value is an array, you use curly braces to declare the array values, as follows:

@SuppressWarnings (value={"Unchecked", "Fallthrough"}) public
	void BBB () {
		
	}

When annotation only a single member, and the member is named "Value=". At this time can omit "value=". The above suppresswarnings annotation can therefore be abbreviated:

When annotation has only a single member and the member is named "Value=", you can omit the "value="
	@SuppressWarnings ({"Unchecked", "Fallthrough"})
	public void CCC () {
		
	}

If the value array declares a number of member values as one, you can omit the curly braces:

If the number of prohibited warnings declared by suppresswarnings is one, you can omit the curly braces
	@SuppressWarnings ("unchecked") public
	void ddd () {
		
	}






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.