Java Basics Understanding Annotation (with @, that is, comments)

Source: Internet
Author: User
Tags deprecated modifier

Understanding of Java Basics Annotation

First, the concept

Annontation is a new feature that Java5 started to introduce. Chinese names are generally called annotations. It provides a secure, comment-like mechanism for associating any information or metadata (metadata) with program elements (classes, methods, member variables, and so on).

More generally it means adding a more intuitive and straightforward description of the elements of the program (classes, methods, member variables) that are not related to the business logic of the program and are intended for use by the specified tool or framework.

Annontation, like a modifier, applies to a declaration statement for a package, type, constructor method, method, member variable, parameter, and local variable.

Second, the principle

Annotation is actually an interface. access to annotation information through the API associated with the reflection mechanism of Java . A related class (a class in a framework or tool) is based on this information to determine how to use the program element or change their behavior.

annotation does not affect the execution of program code, regardless of how the annotation changes, the code is consistently executed.

The Java language interpreter ignores these annotation when it works , so these annotation are "not working" in the JVM, and can only be accessed and processed by the supporting tools for these annontaion types of information.

the similarities and differences between annotation and interface:

1),annotation type use keywords @interface instead of interface.

This keyword declaration implies a message that it inherits the Java.lang.annotation.Annotation interface and does not declare a interface

2),annotation type, method definition is unique, limited.

Methods of the Annotation type must be declared as parameterless, without exception 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,a class type, an enumeration type,a annotation type, or a one-dimensional array of elements from one of the preceding types. You can use default and a default value to declare a member's defaults after a method, andnull cannot be a member default, which is quite different from the method we define in non- annotation types.

The annotation type and its methods cannot use parameters of type annotation, members cannot be generic. Only methods that return a value type of class can use generic in the annotation type , because this method can convert various types to class using class conversions .

3),annotation type and interface have 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, the application situation

Annotation is generally used as an auxiliary approach in software frameworks or tools that take different processes or change the behavior of corresponding program elements (classes, methods, and member variables) based on different annontation annotation information in these tool classes.

For example,annontion is widely used in popular tool frameworks such as Junit, Struts, and Spring . The flexibility of the code is greatly improved.

Iv. Annotation of common standards

starting with the JAVA5 version, it comes with three standard annontation types ,

(1),Override

Java.lang.Override is a marker annotation type, which is used as a labeling method. It illustrates the way that the annotated method overloads the parent class and plays the role of the assertion. If we use this annotation in a method that does not overwrite the parent class method, theJava compiler will alert you with a compilation error.

This Annotaton often adds a supportability verification process when we try to override the parent method and then write the wrong method name.

(2),Deprecated

Deprecated is also a kind of marker annotation. The compiler will not encourage the use of this annotated program element when a type or type member uses the @Deprecated modifier. So using this modification has a certain "continuity": if we use this obsolete type or member in code by inheriting or overwriting it, although the inherited or overwritten type or member is not declared as @Deprecated, the compiler still has to call the police.

Note: This tag is different @Deprecated this annotation type and the @deprecated in Javadoc : The former is recognized by the Java compiler, and the latter is The Javadoc tool identifies a description that is used to generate a document that contains why a program member is outdated, how it should be banned, or substituted.

(3),suppresswarnings

This note can tell the Java compiler to turn off warnings for classes, methods, and member variables.

Sometimes there are some warnings to compile, some hidden bugs for these warnings, some unavoidable , and some warning messages that you don't want to see can be masked by this annotation.

Suppresswarning is not a marker annotation. It has a member of type string[], and the value of this member is the forbidden warning name. For the Javac compiler, a warning name that is valid by the-xlint option is also valid for @SuppressWarings, and the compiler ignores unrecognized warning names.

The annotation syntax allows the annotation name to be followed by parentheses, where the comma-separated name=value is used to assign values to the members of the annotation:

Code:

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

public void Linttrap () {/* Sloppy method body omitted */}

In this example suppresswarnings annotation type only defines a single member, so there is only one simple value={...} As a name=value pair. And because the member value is an array, use curly braces to declare the value of the array.

Note: We can abbreviate annotation in the following scenario : When annotation has only a single member and the member is named "Value=". This can save "value=". For example, the above suppresswarnings annotation is abbreviated:

Code:

@SuppressWarnings ({"Unchecked", "Fallthrough"})

If the number of forbidden warnings declared by Suppresswarnings is one, you can omit the braces:

@SuppressWarnings ("Unchecked")

Five, custom annontation example

Examples involve four classes:

List 1:author.java

Package com.magc.annotation;

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;

/**
* Define author information, name and group
* @author MAGC
*
*/
@Retention (Retentionpolicy.runtime)
@Target (Elementtype.method)
@Documented
Public @interface Author {

String name ();
String Group ();
}

List 2:description.java

/**

*/
Package com.magc.annotation;

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;

/**
* @author MAGC
*
* Define Description Information value
*/
@Retention (Retentionpolicy.runtime)
@Target (Elementtype.type)
@Documented

Public @interface Description {
String value ();
}

List 3:utility.java

Package com.magc.annotation;

@Description (value = "This is a useful tool class")
public class Utility {

@Author (name = "haoran_202", group= "COM.MAGC")
Public String work ()
{
Return "Work over!";
}



}

Note: This is a common Java class that runs @description and @author annotations.

List 3:analysisannotation.java

Package com.magc.annotation;

Import Java.lang.reflect.Method;

public class Analysisannotation {
/**
* Analyze processing of annotation type information at run time
*
*
*/
public static void Main (string[] args) {
try {
Get annotation information through the run-time reflection API
Class Rt_class = Class.forName ("com.magc.annotation.Utility");
Method[] methods = Rt_class.getmethods ();

Boolean flag = Rt_class.isannotationpresent (Description.class);

if (flag)
{
Description Description = (Description) rt_class.getannotation (Description.class);
System.out.println ("Utility ' s Description--->" +description.value ());
for (Method method:methods) {
if (Method.isannotationpresent (Author.class))
{
Author Author = (Author) method.getannotation (Author.class);
System.out.println ("Utility ' s Author--->" +author.name () + "from" +author.group ());

}
}
}


} catch (ClassNotFoundException e) {
E.printstacktrace ();
}
}

}

Note: This is an underlying framework or tool class that is compatible with custom @description and @author, and this class is where you get the information associated with the normal Java class Utility.java, the description and the author.

Run Analysisannotation and the output is:

Utility ' s Description---> This is a useful tool class
Utility ' s Author--->haoran_202 from COM.MAGC

Java Basics Understanding Annotation (with @, that is, comments)

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.