Java annotation and code application examples

Source: Internet
Author: User
The invention cause of Java annotation and the code application example-Linux general technology-Linux programming and kernel information. The following is a detailed description. Annotations can eliminate sample code, make the source code more readable, and provide higher-level error checks. From EJB3 to JUnit4, it is used everywhere. This article will show you how to use it.

Java 5 introduced Annotations to Java, and its use quickly became an indispensable part of modern Java development. Before officially introducing it, let's take a look at why we need to invent an annotation, which is very worthwhile.

Since the birth of Java, people have been solving some problems that they ignored at the beginning: lack of metadata and lack of ability to embed code other than Java into Java source code files. When Java was available, the JavaDoc launched to address these problems finally made it complete. JavaDoc uses the concept of specifically marking comments in the Code, so that it can extract additional information, specifically the document, and convert it into a familiar JavaDoc document. This is a simple technology that everyone can use. First, there will be Doclet to allow people to expand the output of documents. Then Xdoclet, which uses JavaDoc to generate code like a tag, makes the entire process easy. This part is a response to the complexity of J2EE. J2EE originally relied on a lot of sample code (boilerplate code) to bundle objects into the J2EE framework. However, these solutions have some problems. First, the markup in the annotation never enters the final source code, so you cannot find it during runtime unless you generate code to reflect the markup. Secondly, it will add the entire preprocessing layer (ideally, it should be) to a simple compilation process. Finally, annotation-based markup is not easy to check during compilation, nor can it be easily checked by many ides. If you misspell the annotation, the compiler will not notice it, the compiler will only focus on the tags whose names know the exact name.

Java has added annotations to solve all these problems. Annotation is a native metadata tag for Java. Their input is strictly similar to other parts of the Java language and can be identified by reflection, making it easier for IDE and compiler writers to manage them. Now let's look at some annotated code. We start with BaseExample, which is a simple class with only one method -- myMethod:

Public class BaseExample {

Public BaseExample (){}

Public void myMethod (){

System. out. println ("This is the BaseExample ");

}

}

Now we want to extend BaseExample and replace myMethod. The following is the Example1 code for completing this task:

Public class Example1 extends BaseExample {

Public Example1 (){}

@ Overridepublic void myMethod (){

System. out. println ("This is the Example1 ");

}

}

In this way, we have the first comment on myMethod -- @ Override. This is one of a series of built-in annotations. @ Override indicates that "a method must replace one of its superclasses. If this is not done, something goes wrong and the compiler produces an error ". Without @ Override, the code will still work normally, but assume that someone modifies BaseExample so that myMethod has a parameter. If you do not use the @ Override annotation, the code will still be compiled, hiding the problem that subclass does not replace the superclass method. If @ Override exists, you will see an error during compilation.

You may think that "Is it possible that the Language extension does not solve this problem, and additional keywords may exist?" Yes, it may have implemented this, however, this not only does not bring any flexibility to the language, but also causes many source code compatibility problems. This method of annotation avoids changing the Java language itself (in addition to adding @ markup, of course), and can also be placed in different parts of the code, not just in the markup method.

Another thing about annotation is that you can create your own annotation tag, which is exactly what we will discuss right away. Think about the following question: we have some simple Java Beans programs with different string fields. We hope to have some common form display code that can correctly mark these fields with other display prompts (such as width. Now we can write a super class that can extract the data, for example, from a static array with some static support methods in each class, but this also means to force code layering. Using annotations is much easier. Now let's start by defining the FormLabel annotation in FormLabel. java:

Import java. lang. annotation .*;

@ Retention (RetentionPolicy. RUNTIME)

@ Target (ElementType. METHOD)

Public @ interface FormLabel {String label ();

Int width () default 40;

}

The first thing you should note is that Java uses some of its built-in annotations to determine the annotation: @ Retention and @ Target. @ Retention is used to define how long the RetentionPolicy value annotation can survive during build-run. Here we use RUNTIME, which means that the annotation we define will be retained in the code during RUNTIME. RetentionPolicy. SOURCE will be used for an annotation that we want to use by the compiler and then discard. RetentionPolicy. CLASS keeps them in the generated CLASS file, but can be accessed by the Java Virtual Machine (JVM) during runtime.

By default, you can apply annotations anywhere in your code. @ Target annotation allows you to restrict it to a specific part of the code. In this article, we aim at ElementType. METHOD, which means it can only be associated with methods. Other ElementTypes include CONSTRUCTOR, FIELD, LOCAL_VARIABLE, PACKAGE, PARAMETER, and TYPE. Each annotation can be restricted to Java language elements of this TYPE. For example, setting the TYPE option only allows the annotation to be defined. For example:

@ OurAnnotation

Public class OurAnnotatedClass {...

It is worth noting that the @ Target annotation can accept a single ElementType or an ElementType array, if you want to restrict the annotation to a series of language elements.
The following part is the definition of the annotation interface. This is like a common interface declaration, except that we use @ interface to mark it as an annotation. In this interface, we then define the annotation method, just as we want to use the abstract method on the information associated with the annotation, so we have the String label (), it is used for a string attribute called label. If there is no method, the annotation can only be used for "marking", and the @ Overrides annotation is an example. If you only have one attribute, it is best to name it "value", because it works best when an annotation with an unnamed parameter is set. The property can also have default values, such as "int width () de






Fault 40; "is an integer attribute with a default value of 40.

This is the annotation definition. Now we can use it in the code. The following SimpleData class uses it.

Public class SimpleData {

Private String firstname;

Private String lastname;

Private String postcode;

Public SimpleData (){}

@ FormLabel (label = "First Name ")

Public String getFirstname () {return firstname ;}

Public void

SetFirstname (String firstname) {this. firstname = firstname ;}

@ FormLabel (label = "Last Name", width = 80)

Public String getLastname () {return lastname ;}

Public void setLastname (String lastname ){

This. lastname = lastname;

}

@ FormLabel (label = "Postal code", width = 10)

Public String getPostcode () {return postcode ;}

Public void setPostcode (String postcode ){

This. postcode = postcode;

}

}

Of course, if we don't look for comments, they won't make any difference in code execution. All we need is to use the annotation method during running; we use the Reflection API to achieve this purpose. Now let's create a simple processForm method that can search for comments in any object.

Public void processForm (Object o ){

For (Method m: o. getClass (). getMethods ()){

We will define all methods in the class of the object passed to the method. Now, we need to check each method to see if they have FormLabel annotations and whether a String is returned. (To briefly illustrate the problem, we will return more code for all the results ):

If (m. isAnnotationPresent (FormLabel. class )&&

M. getReturnType () = String. class ){

Now we can use the getAnnotation () Method of Method to extract the FormLabel annotation:

FormLabel formLabel =

M. getAnnotation (FormLabel. class );

Now we execute the method to obtain its string value, and access the annotation attribute through the method defined in the annotation interface. Below we will print them out:

Try {

String value = (String) m. invoke (o );

String label = formLabel. label ();

Int width = formLabel. width ();

System. out. printf ("% s [% d]: % s \ n", label, width, value );

} Catch (IllegalArgumentException ex ){

Ex. printStackTrace ();

}

Catch (IllegalAccessException ex ){

Ex. printStackTrace ();}

Catch (InvocationTargetException ex ){

Ex. printStackTrace ();

}

}

}

}

Now we can create new classes containing @ FormLabel annotations and pass them to the processForm method. This is the basis for accessing your own annotations during running.

Now, let's look back at other comments in Java 5. The first is the compiler instruction -- @ Deprecated and @ SuppressWarnings. @ Deprecated indicates a method as a negative enhancement method. It is not recommended to use it in new code to prevent future deletion. @ Deprecated can be used to generate a warning from the compiler.

@ SuppressWarnings will prevent the compiler from warning you in the closed code element, so you can use @ SuppressWarnings at the beginning of the class definition or for specific methods. It can contain parameters to specify the type of the error to be canceled, for example:

@ SuppressWarnings ("unchecked ")

Public List getList (){

List l = new vertex List ();

Return l;

}

Here we cancel a forced conversion of "not checked" between List and List. This is useful when you start programming in Java but do not have non-General code. It is worthwhile to minimize the scope of cancellation when canceling the warning. In the above example, the entire code is canceled. We can compact it to hide only the errors of one statement:

Public List

GetListToo (){

@ SuppressWarnings ("unchecked ")

List l = new vertex List ();

Return l;

}

Note that you need to perform this operation on Java2SE 1.5.06 or later. The previous version does not support @ SuppressWarning.

Other built-in annotations in Java 5 are related to the support for annotations -- @ incluented and @ Inherited. They can all be added to the annotation definition. @ Brief ented: the use of annotation should be reflected in all generated JavaDoc documents. As you may see, annotations and JavaDoc tags are complementary. @ Inherited indicates that the annotation can be Inherited when another class is used to extend the annotation. By default, the annotation cannot be Inherited.

You may wish to use the Java annotation method in your development project. As I mentioned in the introduction, annotations have become an important part of modern Java frameworks and applications. Take JUnit4 as an example, java annotations allow JUnit developers to use more extensive methods for testing, without requiring test writers to enforce Uniform Naming rules. There is also Grails, where annotations can be used to provide information to the "rails-like" framework. There are many capabilities for annotation, but remember that the larger the capability, the greater the responsibility. Annotations are used to provide developers with Tag Information, rather than hide running configurations.

You can use the source code of all examples in this tutorial.

DJ Walker-Morgan is a consulting developer specializing in message delivery and video conferences from Java and users to users.
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.