Three simple annotations and code examples in Java

  • 2020-04-01 03:28:42
  • OfStack

Simple Java annotations

JDK5 provides only three simple annotation types. These three are used for error prevention or warning:

1. The Override
2. Deprecated
3. Suppresswarnings

Note that JDK5(otherwise known as Tiger) doesn't actually have many built-in annotations; Instead, it allows the core Java to support the ability to annotate features. Jsr-175 specifies strictly that it is used to define metadata capabilities. Custom annotation types need to be written by programmers, and other JSR standards write a series of standard annotation types.

Override annotations

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 override a method in the superclass (such as a size error, or an argument error, or a method defined by the subclass itself), the compiler generates an error.

Note: the Override annotation cannot be used to implement methods in an interface in JRE5; JRE6 allows it, and many times JRE5 will declare this error.

Example 1 illustrates overwriting comments:

Java annotation example 1:


public class Test_Override {
 @Override
 public String toString() {
    return super.toString() + " Test using 'Override' annotations ";
 }
}

What happens if the method name is misspelled ? For example, if you rename the toString method to "toString "(all lowercase), you'll get an error message at compile time like this:


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)

Eclipse, of course, simply reports a Red Cross. The IDE is now so good that beginners shouldn't be messing around with the JDK's command line.

Deprecated annotations

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

Java annotation example 2

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


public class Test_Deprecated {
   @Deprecated
   public void doSomething() {
      System.out.println(" Test using deprecated annotations : 'Deprecated'");
   }
}

Next, try calling this method from another class:


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 a deprecated method. Therefore, this method should not be called in general. There is no warning message when compiling the test_deprecated.java file.


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 should block the annotated elements and warning information of all child elements. Could stifle a set of elements and subelements of all warning information. For example, suppose you use the Suppresswarnings annotation on a class unzip a warning, in one of its methods to suppress another warning with Suppresswarnings annotation, then two warnings will be at the method level are suppressed. See sample 3.

Java annotation example 3:


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 example, you use @suppresswarnings to suppress the deprecation warning shown in example 2. Because the method's warnings are suppressed, you will not see the "deprecation" warning again.

Note: it is good to use this annotation on the innermost element. Therefore, if you only want to suppress a warning on a particular method, you should annotate the method, not the class.

Meta-annotations (Java annotation types)

Meta-annotations, which are actually called annotations, come in four types:

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

Target annotation

The Target annotation indicates which Target element the annotation type applies to. It contains the following enumerated type values:

1. @ Target (ElementType TYPE)     -- can be applied to elements of any class
2. @ Target (ElementType FIELD)     -- only for fields or properties
3. @ Target (ElementType METHOD)     -- only applicable to method annotations
4. @ Target (ElementType PARAMETER)     -- applies only to method parameters
5. @ Target (ElementType CONSTRUCTOR)   -- only for constructors
6. @ Target (ElementType LOCAL_VARIABLE)   -- only applicable to local variables
7. @ Target (ElementType ANNOTATION_TYPE)   Specifies that the declaration type itself is an annotation type

Example 4 illustrates the Target annotation:

Java annotation example 4

First, an annotation type named Test_Target with the @target meta-annotation is defined, as follows:


@Target(ElementType.METHOD)
public @interface Test_Target {
   public String doTestTarget();
}

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


public class TestAnnotations {
   public static void main(String arg[]) {
      new TestAnnotations().doTestTarget();
   }
   //Use annotations on methods,OK.
   //In the middle also can not wrap, replace 2 lines and so on,Java ignore the redundant wrap
   @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 methods. Like this:


public class TestAnnotations {
   //This is a mistake, the compilation will not pass because the Level of the annotation is incorrect    //Meta-annotations indicate that only methods can be annotated, and cannot be used to annotate properties
   @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 already defined the annotation  ;   @test_target only works at the method level, and if you try to compile this class, you might get an error message like this:


"TestAnnotations.java":
D:R_AND_DTestAnnotationsrctestmyannotation
   TestAnnotations.java:16:
annotation type not applicable to this kind of declaration at line
16, column 0
@Test_Target(doTestTarget="Hello World !")
^
Error in javac compilation


Related articles: