Java annotations Override, Deprecated, Suppresswarnings detailed

Source: Internet
Author: User
Tags deprecated

first, what is a comment

Speaking of annotations, you have to mention what metadata is (metadata). The so-called meta-data is data data. In other words, metadata is descriptive data. Just like the fields in a data table, each field describes what the data under this field means. The annotations provided in j2se5.0 are the metadata of the Java source code, which means that the comments are descriptive of the Java source code. You can customize the annotations in j2se5.0. When used, the name of the comment is followed by the @.

ii. Pre-defined annotations in j2se5.0

Three annotations are pre-defined in j2se5.0 's Java.lang package. They are the override, deprecated, and suppresswarnings. The following explains their meanings separately.

Override

The purpose of this annotation is to identify whether a method overrides the method of its parent class. So why mark it? Let's take a look at what happens if you don't use the override to identify it.

Assuming there are two classes Class1 and ParentClass1, the ParentClass1 method in MyMethod1 is overwritten with the MyMethod1 method in Class1.

Class ParentClass1{public void myMethod1 () {...}} class Class1 extends ParentClass1 {public void MyMethod2 () {...}} Establish an instance of Class1 and call the MyMethod1 method
ParentClass1 C1 = new Class1 (); C1.mymethod1 (); The above code can be compiled and run normally. However, when writing Class1 code, MYMETHOD1 is mistakenly written as MYMETHOD2, but MYMETHOD1 is not overwritten at the time of invocation. Therefore, the C1.MYMETHOD1 () is called the ParentClass1 MyMethod1 method. Unfortunately, the programmer is not aware of this. Therefore, this may cause a bug.

If we use override to modify the MyMethod1 method in Class1, the compiler will error when MYMETHOD1 is mistakenly written to another method. Therefore, this type of error can be avoided.

Class Class1 extends ParentClass1{@Override//compiler produces an error public void MyMethod2 () {...}} The above code compilation cannot pass, the method of the override annotation must have the same method program in the parent class to compile the pass. This means that only the following code can be compiled correctly.

Class Class1 extends ParentClass1{@Override public void myMethod1 () {...}}

Deprecated

This comment is a markup comment. The so-called tag annotations, which are added to the source program, do not affect the compilation of the program, but sometimes the compiler displays some warning messages.

So what does the deprecated comment mean? If you often write Java programs using an IDE such as Eclipse, you may often see this word in property or method hints. If a word appears in the hint of a class member, it is not recommended to use this class member. Because this class member may be removed in a future JDK version. It is now reserved because of a buffer period for programs that already use these class members. If you go now, these programs will not compile in the new compiler.

Speaking of which, you may have guessed it. Deprecated annotations must be related to these class members. That's right! When you label a class member with deprecated, the class member has some changes in the display. is very obvious in eclipse. Let's see what's changed in Figure 1.


Figure 1 Plus the change of class members after @deprecated in eclipse



As can be seen, there are three places where changes occur. Inside the red box is the part of the change.
1. Method Definition Office
2. Method Reference Place
3. In the list of members displayed

These changes do not affect the compilation, just remind the programmer, this method is to be deleted later, it is best not to use.

Deprecated annotations also have a role. That is, if a class inherits from another class and the override is inherited by the deprecated method of the class, a warning will appear at compile time. The contents of the Test.java are as follows:

Class Class1{@Deprecated public void MyMethod (){}} ' class Class2 extends Class1 {public void MyMethod (){}} The following warning appears for running Javac Test.java:

Note: Test.java uses or overrides outdated APIs.
Note: To learn more, recompile with-xlint:deprecation
Use-xlint:deprecation to display more detailed warning messages:

Test.java:4: Warning: MyMethod () in [deprecation] Class1 is obsolete

public void MyMethod ()
^
1 warnings

These warnings do not affect compilation, just remind you to try not to use the MyMethod method.

suppresswarnings

Things in this world always come in pairs. That is, if the compiler generates a warning message, then there is a suppression compiler generating a warning message.
Suppresswarnings annotations exist for such a purpose. Let's take a look at the following code first.

public void MyMethod (){List wordList = new ArrayList (); Wordlist.add ("foo");}This is a method in a class. Compile it and you will get the following warning.

Note: Testannotation.java is using an unchecked or unsafe operation.
Note: To learn more, recompile with-xlint:unchecked.

The two-line warning message indicates that the list class must be safe to use the pattern before type checking can be performed. There are two ways to not display this warning message. One is to rewrite this method as follows:

public void MyMethod ()
{
list<string> wordList = new arraylist<string> ();
Wordlist.add ("foo");
}

Another way is to use @suppresswarnings.
@SuppressWarnings (value={"Unchecked"})
public void MyMethod ()
{
List wordList = new ArrayList ();
Wordlist.add ("foo");
}
Note that suppresswarnings is not the same as the first two comments. This annotation has a property. Of course, other warnings can also be suppressed, such as:
@SuppressWarnings (value={"Unchecked", "Fallthrough"})

Iii. How to customize annotations

The power of annotations is that it not only makes Java programs self-descriptive, but also allows programmers to customize annotations. The definition and interface of annotations are similar, just a "@" in front of the interface.

Public @interface Myannotation{ }The above code is one of the simplest comments. This comment has no attributes. It can also be understood as a markup comment. Just like the serializable interface, it is a labeled interface with no method defined.

Of course, you can also define annotations with attributes.
Public @interface Myannotation{String value ();}You can use myannotation in the following format
@MyAnnotation ("abc") public void MyMethod (){ }Look at the above code, you may have a question. Why not use value, and write "abc" directly. So who did "abc" actually pass it to? There is actually a convention here. If there is no value for the Write property name, and the comment has the Value property, assign the value to Value property, and if not, a compilation error occurs.

In addition to omitting property names, you can omit attribute values. This is the default value.
Public @interface Myannotation{public String MyMethod (){} default "XYZ";} You can use Myannotation directly
@MyAnnotation//Use default value xyz public void MyMethod (){ }You can also use this
@MyAnnotation (mymethod= "abc") public void MyMethod (){ }
If you want to use more than one property. You can refer to the following code.
Public @interface Myannotation{public enum myenum{A, B, C} publicly myenum.value1 () {} public String value2 () {}} @MyAnnotation (value1=m YANNOTATION.MYENUM.A, value2 = "xyz") public void MyMethod () {} This section discusses how to customize annotations. So what's the use of defining annotations? Is there any way to restrict comments? Can we get a comment from the program? These questions can be found in the answers below.




Iv. How to annotate comments


While the topic of this section is somewhat out of the question, the knowledge it contains can be of great help in designing more powerful Java programs.
In the previous section, we discussed the custom annotations, so we know that annotations are also similar to classes and interfaces in j2se5.0. is a basic part of the program. Since classes and interfaces can be commented on, it is also possible to annotate comments.
Annotations are annotated with ordinary annotations in the same way that they are commented on classes and interfaces. The difference is that j2se5.0 provides 4 annotations separately for comments. They are target, Retention, documented, and inherited. These 4 types of annotations are described separately below.

Target
This annotation is very simple to understand. Since Target's Chinese meaning is "target", we may have guessed that the comment is related to some goal. So what do these goals mean? You can look at the following code first.

@Target (elementtype.method) @interface myannotation {} @MyAnnotation//error using public class Class1 {@MyAnnotation//positive Use public void MyMethod1 () {}} The above code defines a comment myannotation and a class Class1, and uses myannotation to annotate Class1 and MYMETHOD1 respectively. If compiling this code is not possible. Maybe some people are surprised, right Ah! But the problem is on @target (Elementtype.method), because Target uses an enumeration type property, and its value is Elementtype.method. This indicates that myannotation can only be commented on for a method. It cannot be commented on for any other language element. As a result, myannotation naturally cannot comment on Class1.

When it comes to this, you may already have a basic understanding. Target is the language element of Java. such as classes, interfaces, methods, and so on. Of course, target can also restrict other language elements, such as constructors, fields, parameters, and so on. Only annotations to methods and constructors are allowed to be written as:

@Target ({elementtype.method, elementtype.constructor}) @interface myannotation {} Retention
Since annotations can be customized, it is also possible to read comments in the program (how to read comments will be discussed in the next section). However, annotations can only be read if they are saved in the class file. The retention is for setting the comment to be saved in the class file. The following code is a detailed usage of retention.

@Retention (retentionpolicy.source) @interface MyAnnotation1{} @Retention (Retentionpolicy.class) @interface MyAnnotation2 {} @Retention (Retentionpolicy.runtime) @ Interface MyAnnotation3 {} The first part of the code is not to save the comments in the class file, that is, like "//" is filtered out at compile time. The second piece of code is to save comments in the class file only, and ignore them when reading comments using reflection. The third piece of code is to save the comment in the class file, or to read the comment through reflection.

Documented

This annotation is related to the document as well as its name. By default, when you use Javadoc to automatically generate a document, the comments are ignored. If you want to include comments in your document, you must use documented as a document comment.
@interface myannotation{} @MyAnnotation class Class1 {public void MyMethod () {}} When you use Javadoc to generate a document for this code, you do not include @myannotation in it. The resulting document describes the CLASS1 as follows:
Class Class1extends Java.lang.Object And if this is defined myannotation another result will appear. @Documented @interface Myannotation{} generated Document: @MyAnnotation//This line is the class Class1extends added after adding @documented java.lang.Object inherited

Inheritance is one of the main features of Java. The protected and public members in the class will inherit the quilt class, but won't the parent's comment inherit the quilt class? I'm sorry to tell you that, by default, the parent class's comments are not inherited by the quilt class. If you want to inherit, you must add a inherited comment.
@Inherited @interface Myannotation{} @MyAnnotation public class ParentClass {} public class ChildClass extends ParentClass {} In the above code ChildClass As with ParentClass, it has been myannotation annotated.

five, how to read comments using reflection  

    discussed how to customize comments earlier. But what's the use of customizing annotations? This issue is the key to j2se5.0 providing annotations. Custom annotations are of course used. So how to use it? Solving this problem requires using one of the most exciting features of Java: Reflection (Reflect).  
In previous JDK versions, we can use reflection to get information such as the methods of the class, the parameters of the method, and other class members. It is also possible to get the same kind of information as a method in j2se5.0.  

    You must use import java.lang.reflect.* to import and reflect related classes before using reflection.  
    If you want to get comment information for a class or interface, you can use the following code: &NBSP;

Annotation Annotation = TestAnnotation.class.getAnnotation (Myannotation.class);

If you want to get all the comment information, you can use the following statement:
annotation[] annotations = TestAnnotation.class.getAnnotations ();
or
annotation[] annotations = TestAnnotation.class.getDeclaredAnnotations ();
The
Getdeclaredannotations is similar to getannotations, but they differ from the comments that getdeclaredannotations get for the current member, not the inherited one. And Getannotations gets all the annotations that include the inheritance. &NBSP

    If you want to get comments from other members, you can get the member first, and then get the corresponding comment. If you get MyMethod's comments.

method = TestAnnotation.class.getMethod ("MyMethod", null); Annotation Annotation = method.getannotation (Myannotation.class); Note: To use reflection to get comment information, this comment must be annotated with a @Retention (Retentionpolicy.runtime).

Summary
Annotations are a very interesting feature provided by j2se5.0. It is not only interesting, but also very useful. The EJB3 specification is implemented with the help of annotations. This will make EJB3 easier and more humane to implement. and Hibernate3. In addition to using the traditional method of generating hibernate mappings, you can also use annotations to generate hibernate mappings. In short, if you can apply the annotations flexibly to the program, it will make your program more concise and powerful.

Java annotations Override, Deprecated, Suppresswarnings detailed

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.