Three simple annotations and code instances in Java _java

Source: Internet
Author: User

Simple Java Annotations

The JDK5 provides only 3 simple annotation types. These three are all used to prevent errors or reminders, respectively:

1.Override
2.Deprecated
3.Suppresswarnings

Note that JDK5 (another argument, Tiger) actually does not have many built-in annotations; instead, it allows core Java to support the ability of annotation features. It is strictly defined in JSR-175 to define metadata functionality. A custom annotation type needs to be written by the programmer, and the other JSR standards write a series of standard annotation types. Here's an example to explain the three simple annotations in depth.

Override annotation

The Override annotation indicates that the annotated method needs to override the method in the superclass.

If a method uses the annotation, but does not overwrite the method in the superclass (for example, the case is wrong, or the parameter is wrong, or the subclass itself defines the method), the compiler generates an error.

(Note: JRE5 in the implementation of the interface in the method can not use the override annotation, JRE6 allowed, many times JRE5 will report this error).

Example 1 illustrates the overwrite annotation:

Java Annotations Example 1:

Copy Code code as follows:

public class Test_override {
@Override
Public String toString () {
return super.tostring () + "test using ' Override ' annotation";
}
}

What happens if a method name is spelled incorrectly? For example, if you rename the ToString method to "ToString" (all lowercase), you will get an error message similar to the following when compiling:

Copy Code code as follows:

Compiling 1 source file to D:tempnew Folder (2)
Testjavaapplication1buildclasses
D:tempnew Folder (2) testjavaapplication1srctest
Myannotationtest_override.java:24:method does not Override
A method from its superclass
@Override
1 Error
Build FAILED (total time:0 seconds)

Of course, Eclipse will report the Red Fork directly. Now that the IDE is developing well, beginners should not toss the JDK's command line.

deprecated annotation

This annotation indicates that the compiler should display a warning message if the program calls an obsolete (deprecated, deprecated, obsolete) element. Example 2 shows how to use the deprecated annotation.

Java Annotations Example 2

First, create a class and mark a method as obsolete as follows:

Copy Code code as follows:

public class Test_deprecated {
@Deprecated
public void dosomething () {
SYSTEM.OUT.PRINTLN ("Test using deprecated annotation: ' deprecated '");
}
}

Next, try calling this method from another class:

Copy Code code as follows:

public class Testannotations {
public static void Main (String arg[]) throws Exception {
New Testannotations ();
}
Public Testannotations () {
test_deprecated t2=new test_deprecated ();
T2.dosomething ();
}

The DoSomething () method In this example is declared as a deprecated method. Therefore, this method should not be invoked in general. There is no warning message when compiling the Test_deprecated.java file. However, the compiler will give a warning message like this when compiling Testannotations.java (Eclipse will have a warning):

Copy Code code as follows:

Compiling 1 source file to D:tempnew Folder
(2) Testjavaapplication1buildclasses
D:tempnew Folder
(2) Testjavaapplication1srctestmyannotation
TESTANNOTATIONS.JAVA:27:
Warning: [deprecation] dosomething () in
Test.myannotation.Test_Deprecated has been deprecated
T2.dosomething ();
1 warning

suppresswarnings annotation

This annotation tells the compiler to mask the warning message for the annotated element and all child elements. Suppresses all warning messages for a set of elements and child elements. For example, if you use a suppresswarnings annotation on one class to press a warning, and a suppresswarnings annotation to suppress another warning on one of its methods, both warnings will be suppressed at the method level. See Example 3.

Java Annotations Example 3:

Copy Code code as follows:

public class Testannotations {
public static void Main (String arg[]) throws Exception {
New Testannotations (). Dosometestnow ();
}
@SuppressWarnings ({"Deprecation"})
public void Dosometestnow () {
test_deprecated t2 = new test_deprecated ();
T2.dosomething ();
}
}

In this case, the deprecation warning message, shown in Example 2, is pressed using the @SuppressWarnings. Because this kind of warning of this method is pressed, you will not see the "deprecation" warning again.

Note: It is better to use this annotation on the inner element of the layer. So if you just want to suppress a warning on a particular method, you should label the method instead of using annotations on the class.

Meta-annotations (Meta-annotations,java annotation type)

Meta-annotations, which are actually referred to as annotations, contain four of types. respectively:

1.Target
2.Retention
3.Documented
4.Inherited

Target annotation

The target annotation indicates what kind of destination element the annotation type applies to. It contains the following enumeration type values:

1. @Target (Elementtype.type)--elements that can be applied to any class
2. @Target (Elementtype.field)--Applies only to fields or properties
3. @Target (Elementtype.method)--annotations that apply only to methods
4. @Target (Elementtype.parameter)--only applicable to the parameters of the method
5. @Target (Elementtype.constructor)--only applicable to constructors
6. @Target (elementtype.local_variable)--Applies only to local variables
7. @Target (Elementtype.annotation_type)--Indicates that the declaring type is itself a callout type

Example 4 illustrates the target annotation:

Java Annotations Example 4

First, a callout type named Test_target is defined with a @Target meta annotation, as follows:

Copy Code code as follows:

@Target (Elementtype.method)
Public @interface Test_target {
Public String dotesttarget ();
}

Next, create a class that will use the Test_target annotation:

Copy Code code as follows:

public class Testannotations {
public static void Main (String arg[]) {
New Testannotations (). Dotesttarget ();
}
Use annotations on the method, OK.
The middle also can not wrap, change 2 lines and so on, Java ignores extra line wrapping
@Test_Target (dotesttarget= "Hello world!")
public void Dotesttarget () {
System.out.printf ("Testing Target annotation");
}
}

The @Target (elementtype.method) annotation indicates that the annotation type can only be used to annotate the method. If you compile this code, no warning message will be displayed. But what happens if you declare this annotation to a string variable? Just like the following:

Copy Code code as follows:

public class Testannotations {
This is the wrong approach, and compilation does not pass because the annotations are not of the level.
Meta-annotations indicate a method that can only be annotated and cannot be used to annotate attributes
@Test_Target (dotesttarget= "Hello world!")
Private String str;
public static void Main (String arg[]) {
New Testannotations (). Dotesttarget ();
}
public void Dotesttarget () {
System.out.printf ("Testing Target annotation");
}
}

The only change is that the annotation declaration moves from the method level to the field level, which is incorrect. Because you have defined annotations @Test_Target only apply at the method level, you may get an error message if you try to compile this class:

Copy Code code as follows:

"Testannotations.java":
D:r_and_dtestannotationsrctestmyannotation
Testannotations.java:16:
Annotation type not applicable to this kind of declaration at line
-Column 0
@Test_Target (dotesttarget= "Hello world!")
^
Error in Javac compilation

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.