Reprinted: https://www.cnblogs.com/Johness/archive/2013/04/17/3026689.html
1. An annotation is essentially a markup. Compared with xml configuration, there is only a difference in the way
2. The annotation itself is also a type and also needs to be declared
package annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Custom annotations to configure methods * * @author Johness * */ @Retention(RetentionPolicy.RUNTIME) // Indicates that the annotation still exists at runtime @Target(ElementType.METHOD) // Indicates that the annotation can be used on the method public @interface SayHiAnnotation { String paramValue() default "johness"; // means my annotation needs a parameter named "paramValue" default value is "johness" }
3. Use annotations
package element; import annotation.SayHiAnnotation; /** * The class of the element to use SayHiAnnotation * Since we defined that only methods can use our annotations, we use multiple methods for testing * * @author Johness * */ public class SayHiEmlement { // normal method public void SayHiDefault(String name){ System.out.println("Hi, " + name); } // method using annotations and passing in parameters @SayHiAnnotation(paramValue="Jack") public void SayHiAnnotation(String name){ System.out.println("Hi, " + name); } // method using annotation and using default parameters @SayHiAnnotation public void SayHiAnnotationDefault(String name){ System.out.println("Hi, " + name); } }
4. Reflection to get the annotated method and perform the corresponding operation
package Main; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import element.SayHiEmlement; import annotation.SayHiAnnotation; public class AnnotionOperator { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { SayHiEmlement element = new SayHiEmblement(); // Initialize an instance for method invocation Method[] methods = SayHiEmlement.class.getDeclaredMethods(); // get all methods for (Method method : methods) { SayHiAnnotation annotationTmp = null; if((annotationTmp = method.getAnnotation(SayHiAnnotation.class))!=null) // Check if our annotation is used method.invoke(element,annotationTmp.paramValue()); // If our annotation is used, we call the method with the "paramValue" parameter value in the annotation as a method parameter else method.invoke(element, "Rose"); // If we don't use our annotation, we need to use the normal way to call the method } } }
5. Results
Hi, Jack Hi, johness Hi, Rose