Crazy Java Learning Note (Annotation)-----------(note) The first article

Source: Internet
Author: User
Tags deprecated modifiers

Starting with JDK1.5, Java has added support for metadata (MetaData), which is annotation (note), which differs from the single-line comment and text annotation in a Java program and has a certain connection. In fact, the annotation we're talking about now is a special tag in the code that can be read at compile, class load, run time, and do the appropriate processing. through annotation, the program developer can embed some supplemental information in the source file without changing the original logic. Code analysis tools, development tools, and deployment tools can be used to verify or deploy these additional information.


Annotation provides a way to set elements for program elements, and in some ways annotation is used like modifiers, which can be used to decorate packages, classes, constructors, methods, member variables, parameters, and declarations of local variables that are present annotation " Name=value "Alignment.


Attention


Annotation is an interface that a program can use to get the annotation object of a specified program element by reflection, and then get the metadata in the comment by annotation object. We need to pay attention to the use of annotation, some annotation refers to the Java.lang.Annotation interface, and some refers to the annotation itself.

Annotation can be used to set meta data for program elements (classes, methods, member variables). It is worth pointing out that annotation can not affect the execution of program code, regardless of the increase, delete annotation, the code is consistently executed. If you want to allow Annotation in your program to function at run time, you can only access and process the information in Annotation with some matching tool, and the tools to access and process Annotation are collectively known as APT (Annotation processing Tool).

I. Basic annotation
Annotation must be handled with tools that are responsible for reading the metadata contained in the annotation, and the tool will add additional functionality based on those metadata. Before the system learns the new annotation syntax, take a look at the usage of the three basic annotation provided by Java: Add the @ symbol in front of it with annotation and use that annotation as a modifier to decorate the program elements it supports .

The three basic annotation are as follows


@Override
@Deprecated
@SuppressWarings

(these three basic annotation are defined under the Java.lang package)


Let's use the three annotation in turn.

(1) Restricting the overriding of the parent class method @Override
@Override is used to specify method overrides, which can force a subclass to overwrite a method of the parent class. Use @override in the following program to specify subclasses Apple's Info method must override the parent class method
Note: @Override annotation can only be used to act on methods and cannot be used for other program elements

Instance:

<span style= "FONT-SIZE:18PX;" >class shape{    void Draw () {       System.out.println ("shape");}    } class Circle extends shape{    // The @override ellipsis effect is the same    @Override    void Draw () {       System.out.println ("Round");}    } </span>


<span style= "FONT-SIZE:18PX;" >public class  fruit{public void info () {  System.out.println ("info method for fruit ...");}} Class Apple extends fruit{@Override public void info () {  System.out.println ("Apple rewriting fruit Info method ...");}} </span>



Role:

Compile the above program, may not see the program in the @override have any effect. Because the role of @override annotation is to tell the compiler to check the method, and to find out if the parent class contains a method overridden by the method, the compilation error occurs. This annotation is mainly to help us avoid some of the low-level mistakes, such as we have the above Apple class info method accidentally written inf0 () method, such a "low-level error", may lead to late troubleshooting a huge obstacle.

(2) Mark obsolete @Deprecated
@Deprecated is used to indicate that a program element (class, method, and so on) is obsolete, and the compiler will be warned when other programs use obsolete classes. The following program specifies that the info method in the Apple class is obsolete, and the compiler will give a warning when using the Apple class's info method in other programs.

Instance:

<span style= "FONT-SIZE:18PX;" >public classtest{public    static void Main (string[] args) {       ///below calls shape's draw method, the compiler gives warning       new shape (). Draw ();    } }   class shape{    @Deprecated    void Draw () {       System.out.println ("Draw a Shape");}    } </span>

<span style= "FONT-SIZE:18PX;" >class apple{//define Info method obsolete @Deprecated public void info () {  System.out.println ("Apple info Method");}} public class deprecatedtest{public static void Main (string[] args) {  ///The following using the info method will be warned by the compiler of  new Apple (). info ( ); }}</span>
<span style= "FONT-SIZE:18PX;" > </span>

 

(3) @SuppressWarnings suppress compiler warnings
@SupressWarnings indicates that the program element identified by the annotation (and all child elements in the program element) suppress the specified compiler warning. @SuppressWarnings will always work on all child elements of the program element, such as using @suppresswarning to identify a class to suppress a compiler warning, while identifying a method in the class that cancels another compiler warning. Both compiler warnings will be canceled at the same time in this method.

 In general, if you use a collection that does not have a generic restriction in your program that will cause a compiler warning, you can use @suppresswarnings Annotation to avoid this compiler warning, and the following program cancels compiler warnings that do not use generics.

<span style= "Font-size:18px;color: #000000;" > @SuppressWarnings (value= "Unchecked") public class suppresswarningstest{public static void Main (string[] args) {  list<string> myList = new ArrayList ();   } }</span>


<span style= "FONT-SIZE:18PX;" >//shutdown Compiler Warning @SuppressWarnings ("Unchecked") public class test{public    static void Main (String[]args) {       list<string> templist = new ArrayList ();    } }</span>


Description
A. Use @suppresswarnings in your program to close all compiler warnings in the Suppresswarningtest class, and you will not see any compiler warnings when compiling the program.

B. When we use @suppresswarnings annotation to turn off compiler warnings, be sure to use the name=value pair in the interpolation to set the value for the annotation member variable.

Two. Custom annotation
We have described how to use the three standard annotation under the Java.lang package. Here's how to define Annotation and use Annotation to do some real-world functionality.

(1) Definition annotation
When defining a new annotation type, use the @interface keyword (add the @ symbol before the original interface key word), which defines the new annotation type. Defining a new annotation type is much like defining an interface.

The following code defines a simple annotation

<span style= "FONT-SIZE:18PX;" >//defines @testpublic class myclass{with the @test modifier class ...} </span>



After defining the annotation, the annotation can be used anywhere in the program, and the syntax when using annotation is very similar to public and final, and can often be used to modify the definitions of classes, methods, variables, interfaces, etc. in a program.
Usually we put annotation before all modifiers, and because of the possibility of specifying a value for other member variables when using annotation, the length of the annotation may be longer, so annotaion is usually put in another line.
Such as

<span style= "FONT-SIZE:18PX;" >//defines @testpublic class myclass{with the @test modifier class ...} </span>


By default, annotation can be used to decorate any element, including classes, interfaces, methods, and so on. The following program uses @testannotation to modify the method

public class myclass{   //Use the @testannotation adornment method   @Test public   void info ()   {...   }}


Annotation can be not only this simple annotation,annotation but also with the staff variables, annotation member variables are declared in the annotation definition with no parameters. Its method and return value define the name and type of the member.


The following code can define a annotation with member variables
Public @interface MyTag
{
//define two member variables annotation
member variables in//annotation are defined in the form of a method
String name ();
int Age ();
}

 

Careful observation: The code above defines annotation is very similar to the syntax for defining an interface, except that the above mytag is defined using the @interface keyword, and the interface uses interface to define

Once you have defined a member variable in annotation, you should specify a value for the annotation member variable when you use the annotation.

As shown in the following code


public class Test
{
      // When using annotation with member variables, you need to pay the value of the member variable
      mytag (name= ' Heyitang ', age=30)
      public void info ()
      {
  ...
      }
}

We can also specify an initial value for a member variable of the annotation, specifying the initial value of the member variable to use the default keyword. The following code defines the MyTag annotaion, which contains two members: Name and age, and the two Narimoto variables use default to specify the defaults
public @interface mytag
{
    //defines two member variables for annotaion
    /Specify initial values with default of two member variables
    String name () default "Yeeku";
    int age () default;
}
 
If you specify a default value for the annotation member variable, use that annotation to not specify values for the member variables, but instead to use the default values directly, as shown in the following code
public class Test
{
      //Use annotation
  with member variable     // Because its member variable has a default value, you can not specify a value for the member variable
      @MyTag
      public void info ()
      {
              ...
      }
}

of course, the annotation we're introducing can include member-specified values, and if MyTag has a value assigned to a member variable, the default value won't work


Summary
depending on whether the annotation we're introducing can contain member variables , we can divide the annotation into the following two categories
1. Mark Annotation: A annotation type with no member variable is called a tag. This kind of annotation only uses its own existence or not to provide information to us. As described earlier @override, @Test and other annotation
2. meta-data annotation: Those annotation that contain member variables, because they can accept more metadata, are also called metadata annotation


(2) Extract annotation
As mentioned earlier: Java uses the annotation interface to represent the annotation preceding the element, which is the parent interface for all annotation types. In addition, Java has added a annotationelement interface under the Java.lang.reflect package, which represents the program element in the program that can accept annotations, and the interface Master has the following implementation classes.

class: Classes Definition
Constructor: constructor definition
Field: Member variable definition for class
method: Methods definition of Class
Package: Packages definition for class

The Annotationelement interface is the parent interface for all program elements (such as Class,method,constructor ). So the program can call the following three methods of the object to access the annotation information after it has obtained the Annotationelement object (such as Class,method, and constructor) of a class through reflection.


Getannotation ( class<t> annotationclass): Returns a comment of the specified type that exists on the program element
Annotation[] Getannotations: Returns all comments that exist on the program element
boolean isannotationpreset (class<? extends annotation> annotationclass ): Determines whether the program element contains a comment of the specified type, returns True if it exists, or false

(3) Examples of using annotation
Here are two examples of using annotation, the first annotation testable does not have any member variables, it is only a token annotation, and its purpose is to flag which methods are testable.
Testable.java the source file.

Testable.java source file import java.lang.annotation.*; @Retention (retentionpolicy.runtime)   @Target (elementtype.method)//Definition testable Annotation will be extracted by Javadoc tool @documentedpublic @interface testable{}


The above program defines a tag testable Annotation, which uses @retention and @target two system meta annotations when defining the Annotation, where the @retention comment indicates how long the Testabel comment can be retained, The @target annotation specifies the target that the testable can modify (only the method).

There are 8 methods defined in the following mytest test cases, 8 methods are not very different, and four methods use @testable annotations to mark these methods as testable

public class mytest{//Use the @testable tag comment to specify that the method is testable @Testable public static void M1 () {} public static void M2 () {}   //Make Use the @testable tag annotation to specify that the method is testable @Testable public static void M3 () {         throw new RuntimeException ("Boom");  void M4 () {}       //Use @testable tag comment to specify that the method is testable @Testable public static void M5 () {} public     static void M6 () {}//Use @t The estable tag Note specifies that the method is testable @Testable public static void M7 () {             throw new RuntimeException ("Crash");   }        public static void M8 () {}}



As mentioned earlier, just using annotations to mark program elements has no effect on the program, which is an important principle of annotations, and in order for these annotations to work in the program, we must provide a comment processing tool for those annotations.

The following annotation processing tool parses the target class and, if the method in the target class uses the @testable annotation adornment, runs the test method by reflection

Import java.lang.reflect.*;p ublic class testprocessor{public static void process (String clazz)  throws classnotfoundexception {  int passed = 0;  int failed = 0;  Iterates through all the methods of the Obj object for  (method M:class.forname (Clazz). GetMethods ())  {   //If the @testable tag is included in the comment if   ( M.isannotationpresent (Testable.class))   {    try    {     //Call M method     M.invoke (null);     Passed plus 1     passed++;    }    catch (Exception ex)    {     System.out.printf ("method" + M + "Run failed, exception:" + ex.getcause () + "\ n");     failed++  ;  }}} Statistical test results  System.out.printf ("Total run:" + (passed + failed) + "method, where: \ n" +   "failed:" + failed + ", \ n" + "    succeeded:" + P Assed + "A!" \ n "); }}


Reference post: http://blog.sina.com.cn/s/blog_4c925dca0100hseu.html

http://blog.csdn.net/zhai56565/article/details/40503743

Crazy Java Learning Note (Annotation)-----------(note) The first article

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