Use case details of the Java annotation

  • 2020-05-26 08:37:13
  • OfStack

Use of Java annotations

The use of annotations is very simple. Just indicate a comment where it is needed, such as on a method:


public class Test { 
@Override 
public String tostring() { 
return "override it"; 
} 
}

For example, annotations on a class:


@Deprecated 
public class Test { 
}

So Java's built-in annotations can be used directly, but many times we need to define our own annotations. For example, spring commonly USES a large number of annotations to manage dependencies between objects. Let's see how to define one of your own annotations, and implement one that injects a string into a class via @Test and a string into a method via @TestMethod.

1. Create an Test annotation that declares the class to be acted on and retained at runtime, with the default value of default.


@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Test { 
String value() default "default"; 
}

2. Create TestMethod annotations that declare the action on the method and leave it at runtime.


@Target({ElementType.METHOD}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface TestMethod { 
String value(); 
}

3. Test class, after running, output default and tomcat-method strings. Since @Test has no incoming value, output the default value, while @TestMethod outputs the injected string.


@Test() 
public class AnnotationTest { 
@TestMethod("tomcat-method") 
public void test(){ 
} 
public static void main(String[] args){ 
Test t = AnnotationTest.class.getAnnotation(Test.class); 
System.out.println(t.value()); 
TestMethod tm = null; 
try { 
tm = AnnotationTest.class.getDeclaredMethod("test",null).getAnnotation(TestMethod.class); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
System.out.println(tm.value()); 
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: