Java basics Annotation

Source: Internet
Author: User

 

 

IConcept

Annontation is a new feature introduced by Java 5. The Chinese name is generally called annotation. It provides a secure annotation-like mechanism to associate any information or metadata (metadata) with program elements (such as classes, methods, and member variables.

The more common meaning is to add a more intuitive and clear description of the program elements (classes, methods, and member variables). The description information is irrelevant to the business logic of the program, it is used by the specified tool or framework.

Like a modifier, Annontation is used in declaration statements of packages, types, constructor methods, methods, member variables, parameters, and local variables.

II, Principle

Annotation is actually an interface. Access annotation information through APIS related to the Java reflection mechanism. Related classes (classes in frameworks or tools) Determine how to use the program elements or change their behavior based on the information.

Annotation does not affect the execution of program code. No matter how annotation changes, the code is always executed.

The Java interpreter ignores the annotation during work. Therefore, the annotation in JVM does not work, you can only access and process annontaion-type information through supporting tools.

Differences between Annotation and interface:

1) The Annotation type uses the keyword @ interface instead of interface.

This keyword Declaration implies a message: it inherits the java. lang. annotation. Annotation interface, not an interface

2) The Annotation type and method definition are unique and restricted.

Methods of the Annotation type must be declared as non-parameter and thrown without exceptions. These methods define annotation members: the method name is a member name, and the return value of the method becomes the member type. The Return Value Type of the method must be the primitive type, Class type, enumeration type, annotation type, or a one-dimensional array with one of the preceding types as elements. After the method, you can use default and a default value to declare the default value of the member. null cannot be the default value of the member, which is very different from the method defined in non-annotation type.

The Annotation type and its method cannot use the annotation type parameter or the member cannot be generic. Only methods whose return value type is Class can use generic in the annotation type, because this method can use Class conversion to convert various types to Class.

3) The Annotation type is similar to the interface.

They can define constants and static member types (for example, enumeration type definition ). The Annotation type can also be implemented or inherited as an interface.

3., Application scenarios

Annotation is generally used as an auxiliary method in a software framework or tool, in these tool classes, different processes or changes to corresponding program elements (classes, methods, and member variables) are taken based on different annontation annotation information.

For example, annontion is widely used in popular tool frameworks such as Junit, Struts, and Spring. This greatly improves code flexibility.

 Thu, Common standardAnnotation

Java 5 has three standard annontation types,

(1) Override

Java. lang. Override is a marker annotation type and is used as a annotation method. It indicates that the labeled method overload the parent class method and plays the role of assertion. If we use this annotation, the java compiler will warn you of a compilation error when a method that does not overwrite the parent class method.

This annotaton often adds a guaranteed verification process when we try to override the parent class method and make sure that the method name is wrong.

(2) Deprecated

Deprecated is also a marker annotation. When a type or type member is modified with @ Deprecated, the compiler does not encourage the labeled program element. Therefore, using this modifier has a certain degree of "continuity": if we use this obsolete type or member in code by inheritance or override, although the inherited or overwritten type or member is not declared as @ Deprecated, the compiler still needs to issue an alert.

Note: The annotation type @ Deprecated is different from the @ deprecated tag in javadoc. The former is recognized by the java compiler, the latter is identified by the javadoc tool to generate documents (including descriptions of why Program Members are outdated, how they should be disabled or replaced ).

(3) SuppressWarnings

This annotation tells the Java compiler to disable warnings for classes, methods, and member variables.

Sometimes some warnings are generated during compilation. Some of these warnings hide bugs, some are unavoidable, and some do not want to see warning information, you can use this annotation to block them.

SuppressWarning is not a marker annotation. It has a member of the String [] type. The value of this Member is the forbidden warning name. For the javac compiler, the warning names that are valid by the-Xlint option are also valid for @ SuppressWarings, And the compiler ignores unrecognized warning names.

The annotation syntax allows annotation names followed by parentheses. The name = value pairs separated by commas are used to assign values to annotation members:

Code:

@ SuppressWarnings (value = {"unchecked", "fallthrough "})

PublicvoidlintTrap () {/* sloppy method body omitted */}

In this example, the SuppressWarnings annotation type only defines a single member, so only one simple value = {...} is used as the name = value pair. Since the Member value is an array, braces are used to declare the array value.

Note: We can abbreviated annotation in the following cases: when annotation only has a single member and the member name is "value = ". In this case, you can save "value = ". For example, abbreviated SuppressWarnings annotation:

Code:

@ SuppressWarnings ({"unchecked", "fallthrough "})

If the number of forbidden warnings declared by SuppressWarnings is one, you can ignore the braces:

@ SuppressWarnings ("unchecked ")

V., CustomAnnontationExample

The example involves four classes:

Listing 1: Author. java

Packagecom. magc. annotation;

Importjava. lang. annotation. incluented;
Importjava. lang. annotation. ElementType;
Importjava. lang. annotation. Retention;
Importjava. lang. annotation. RetentionPolicy;
Importjava. lang. annotation. Target;

/**
* Defines the author information, including name and group.
* @ Authormagc
*
*/
@ Retention (RetentionPolicy. RUNTIME)
@ Target (ElementType. METHOD)
@ Brief ented
Public @ interfaceAuthor {

String name ();
String group ();
}

Listing 2: Description. java

/**
*
*/
Packagecom. magc. annotation;

Importjava. lang. annotation. incluented;
Importjava. lang. annotation. ElementType;
Importjava. lang. annotation. Retention;
Importjava. lang. annotation. RetentionPolicy;
Importjava. lang. annotation. Target;

/**
* @ Authormagc
*
* Define description value
*/
@ Retention (RetentionPolicy. RUNTIME)
@ Target (ElementType. TYPE)
@ Brief ented

Public @ interfaceDescription {
String value ();
}

Listing 3: Utility. java

Packagecom. magc. annotation;

@ Description (value = "this is a useful tool class ")
PublicclassUtility {

@ Author (name = "haoran_202", group = "com. magc ")
PublicString work ()
{
Return "work over! ";
}



}

Note: This is a common Java class and runs the @ Description and @ Author annotations.

Listing 3: AnalysisAnnotation. java

Packagecom. magc. annotation;

Importjava. lang. reflect. Method;

PublicclassAnalysisAnnotation {
/**
* Analyze and process annotation-type information at runtime
*
*
*/
Publicstaticvoidmain (String [] args ){
Try {
// Obtain annotation information through the runtime reflection API
Class rt_class = Class. forName ("com. magc. annotation. Utility ");
Method [] methods = rt_class.getMethods ();

Booleanflag = 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 a basic framework or tool class supporting custom @ Description and @ Author. Through this class, you can obtain information associated with General Java Utility. java, that is, Description and Author.

Run AnalysisAnnotation and the output result is:

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

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.