A comprehensive analysis of annotations and annotations in Java _java

Source: Internet
Author: User
Tags class definition deprecated readline

Annotations
One, what is Annotation? (note or comment)
Annotation, the exact translation should be--annotation. and the annotation function is completely different.
Annotation is a feature introduced in JDK5.0 and later versions. With classes, interfaces, enumerations at the same level, you can become a type of java.
The syntax begins with a @
In simple terms,
A note is a memory or suggestive description of a programmer's class, method, or attribute of the source code (for example, what this method does), and is given to people to see.
Annotations are an understandable part of the Java compiler and are for the compiler to see.
Take a simple example to see the use and function of annotations.
@Override is a more common Java built-in annotation that is used to check that the methods defined in subclasses are correct when compiling code.

package annotation; 
 
Public abstract class Animal {public 
 
  abstract void Eat (); 
} 

package annotation; 
 
public class Cat extends animal{ 
 
  @Override public 
  void Eat (String food) {  
  } 
} 

Here in the subclass cat The Eat method is annotated as a method of overwrite the parent class, but it has one more argument than the parent class method.
If you are editing in Eclipse, you will be prompted with a red fork. (Code compilation does not pass through).
If you remove @override annotations, the compilation is fine, but the Eat method in Cat is a new method of this class, not inherited from the parent class.

Second, common Java built-in annotations
contains @override, and what are the common Java built-in annotations?
1. @Deprecated
Annotations are not recommended and can be used on methods and classes.
Basically, this method and class are deprecated for some reason above the upgrade or performance, but must be retained for compatibility or other reasons.
So I'm going to make this remark.
There are a number of examples in the Java API, in which the method makes the annotation, and the source code will see the new method of substitution.
When you write code in Eclipse, the method that adds this annotation is added to the deletion line wherever it is declared and invoked.

2. @Override

3. @SuppressWarnings
Ignore the warning.
If your code has some warning in transition or other parts, but you want to ignore these warnings, you can use this annotation.
1 deprecation use a warning when using a class or method that is not in favor

2) unchecked performs unchecked conversion warning

3) Fallthrough The warning that occurs when the program continues to execute other case statements when a break operation is not added to the case after using the switch operation

4 path when setting an error class path, source file path, warning

5) Serial warning when a SERIALVERSIONUID definition is missing on a serializable class

6) fianally warning when any finally clause does not complete properly

7 All warnings about all the above situations

Three, custom annotations
In addition to the built-in annotations provided by Java itself, Java also provides the ability to customize custom annotations. The
is defined by using annotations to define annotations, and the annotations used to define annotations are called meta annotations. The
main meta annotations have the following four: @Target; @Retention; @Documented; @Inherited
1. @Target indicate where the annotation is used, on a class, on a method, or on a property, etc.
possible The Elemenettype parameters include:
Elemenettype.constructor constructor declaration
Elemenettype.field Domain declaration (including enum instance)
Elemenettype.local_va riable local variable declaration
Elemenettype.method Method declaration
Elemenettype.package Package declaration
Elemenettype.parameter Parameter declaration
Elemenetty Pe. Type class, an interface (including the annotation type), or an enum declaration
2. @Retention represents the level at which the note information is saved
optional retentionpolicy parameters include:
Retentionpolicy.source annotations will be The compiler discards the
Retentionpolicy.class annotation as it is available in the CLASS file, but is discarded by the VM
Retentionpolicy.runtime VM will also retain annotations at run time, so you can read the annotation information through the reflection mechanism.
3. @Documented, whether or not to include this annotation when DOC is generated
include this note in Javadoc
4.  @Inherited
allow subclasses to inherit annotations in the parent class
see some simple definitions for examples:

package annotation; 
 
Import java.lang.annotation.Documented; 
Import Java.lang.annotation.ElementType; 
Import java.lang.annotation.Inherited; 
Import java.lang.annotation.Retention; 
Import Java.lang.annotation.RetentionPolicy; 
Import Java.lang.annotation.Target; 
 
@Target (elementtype.method) public 
@interface myannotation { 
  String value (); 
} 
 
@Retention (retentionpolicy.source)  
@interface MyAnnotation1 {}  
 
@Retention (Retentionpolicy.class)  
@interface MyAnnotation2 {}  
 
@Retention (retentionpolicy.runtime)  
@interface MyAnnotation3 {} 
 
 
@ Documented 
@interface MyAnnotation4 {} 
       
@Inherited 
@interface MyAnnotation5 {} 

Iv. Examples of Use:

package annotation; 
 
Import java.lang.annotation.Annotation; 
 
@MyAnnotation3 public 
class Testannotation {public 
  static void Main (string[] args) { 
    //TODO auto-generated Method Stub 
    Annotation Annotation = TestAnnotation.class.getAnnotation (myannotation3.class); 
    System.out.println (Annotation.tostring ()); 
  } 
 
 

Print out the result: @annotation. MyAnnotation3 ()
If the above example replaces the use of MyAnnotation1 and MyAnnotation2, the value of the annotation that is taken is null, which is the retentionpolicy difference.

V. The role of annotation

Introduction to this, you can sum up the role of annotation.
The basis can be broadly divided into three categories:
1. Writing Documents
2. Code Analysis
3. Compile check
However, the open source framework gives it more effect
Like what:
Hibernate, annotation configuration,

@Column ("AA") 
private String xx; 

This is similar to XML configuration and simplifies configuration in programs
Relative to the part of the metadata from the XML file moved to the code itself, in a place to manage and maintain.
How is the interior implemented? --Java reflection mechanism, similar to the above examples.

Comments
Although annotations and annotations differ only by one word, usage varies widely.
Or that sentence, note to the compiler to see, comments are for people to see.
Based on this, for a method:
1. The function of this method, input, output description clearly can be, more can add some author ah, version ah so some information
2. The appearance of the annotation arrangement is some
Do these two points should be OK. As an example:

/******************************************************************************* 
* NAME:     usage 
* Description:xxx 
* ARGUMENTS:  N/A 
* return:    
* AUTHOR:    oscar999 
* VERSION:   V0.1 
*******************************************************************************/ 

It seems to be a good comment ^ ^.

But for the Java language, annotations are given more functionality. Is that you can use Javadoc to export annotations in your code to an HTML file.
If your code is a highly shared code, this document is a reference document for the API, similar to the Java API.
Therefore, in order to produce such a document, it is necessary to follow the Java definition of some annotation specifications to produce a specification of the document.

Standard annotations for Java class methods
or from the annotation of the method of the class.

  /** 
   * Read a line of text. A line are considered to being terminated by any one 
   * 's a line feed (' \ n '), a carriage return (' \ R '), or a carriage Retu RN 
   * followed immediately by a linefeed. 
   * 
   * @param   ignoreLF1 If True, the next ' \ n ' would be skipped 
<pre code_snippet_id= "74911" Snippet_file_name = "blog_20131120_2_8365599" name= "code" class= "java" >   * @param   ignoreLF2 If True, the next ' \ n ' would be skipped </pre>   * *   @return   A String containing the contents of the line, not including   * any       line- termination characters, or null if the end of the   *       Stream has been reached   *   * @see    Java.io.Line Numberreader#readline ()   *   * @exception ioexception If an I/O error occurs * *    

(Don't pay attention to the meaning of the above annotation, only the style that it defines)
1. First look at the top "read a line of text." A line. "This paragraph is a description of this method.

The section at the front of the first period, that is, "Read a line of text." appears in the method summary

2. @param defines the input parameters of the method (which can be added) and appears in the method details. (parameter and parameter descriptions are separated by spaces, and the resulting document is converted to-)

3. Description of the return value of the @return
4. Description of @see Reference
5. Description of @exception Exception thrown
Aesthetic considerations, not the same kind of label can be changed to display, such as @param and @return directly empty line.

Java Class Standard Annotation
the annotation of the class and the method annotation are in the same format. The difference places:
1. Placement is in a different position. The annotation of the class is placed above the class definition, and the annotation of the method is placed above the method definition.
2. The annotation comparison of a class uses a label such as @version @author @since.
Look at the template

/** 'll buffer the input from the specified file. Without buffering, each 
* invocation of a read () or readLine () could cause to is read 
from the * file, convert Ed into characters, and then returned, which can be very 
* inefficient. 
* * * 
Test Description 
* * 
<p> Programs-datainputstreams for textual input can is localized by 
* Replacing each datainputstream with a appropriate bufferedreader. 
* * 
@see filereader 
* @see inputstreamreader * * * 
@version 0.1, 11/20/13 
* @author  oscar999 
* @since  JDK1.5 * * 
 

The effect shown in doc is:
Similarly, the first sentence of the description appears in the class outline.

The details of the class appear as follows:

It is noteworthy that the use of <p> in description. If you do not add <p>, in the Java code regardless of whether there is a newline, the resulting doc does not change lines. Plus <p>, a newline appears in Doc.

Third, to supplement
to add, the way to create Javadoc:
1. Named row mode: Javadoc + parameters

2. Export using the Eclipse IDE
If you right-click on a source file or project in the Eclipse IDE, select Export--->
Java--> Javadoc can be generated.

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.