Use of Java annotations
The use of annotations is very simple. You just need to indicate annotations where the annotations are needed, such as annotations on the method:
public class Test { @Override public String tostring() { return "override it"; } } For example, annotation on the class:
@Deprecated public class Test { }Therefore, Java built-in annotations can be used directly, but many times we need to define some annotations ourselves. For example, common spring uses a large number of annotations to manage the dependencies between objects. Let’s see how to define your own annotation. The following implements annotation: inject a string into a certain class through @Test, and inject a string into a method through @TestMethod.
1. Create a Test annotation, declare it to act on the class and retain it until runtime, and the default value is default.
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Test { String value() default "default"; } 2. Create a TestMethod annotation, declare it to act on the method and retain it until runtime.
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface TestMethod { String value(); } 3. Test class, after running, output two strings default and tomcat-method. Because @Test does not pass in value, the default value is output, 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 it can help you. Thank you for your support for this site!