Package annotition;
Import java.lang.annotation.Documented;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
@Target (Elementtype.type)
@Retention (Retentionpolicy.runtime)
@Documented
Public @interface ClassInfo {
String name () default "";
}
++++++++++++++++++++++++++++++++++
Package annotition;
Import java.lang.annotation.Documented;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
@Target (Elementtype.method)
@Retention (Retentionpolicy.runtime)
@Documented
Public @interface MethodInfo {
String value () default "";
}
++++++++++++++++++++++++++++++++++++++++++++++++
Package annotition;
@ClassInfo (name = "Hellow World")
public class Myannotition {
@MethodInfo ("Hello")
public void Java () {}
}
+++++++++++++++++++++++++++++++++++++++++++++++
Package annotition;
Import static org.junit.assert.*;
Import java.lang.annotation.Annotation;
Import Java.lang.reflect.Method;
Import Junit.framework.Test;
public class Annotationparse {
public static void Parse () {
Class clazz = Myannotition.class;
ClassInfo annotations exist on this class
if (Clazz.isannotationpresent (Classinfo.class)) {
Get the annotations of a class from a class
ClassInfo ClassInfo = (ClassInfo) clazz.getannotation (Classinfo.class);
Output the Name property of the annotation
System.out.println (Classinfo.name ());
}
Get all the methods of the class
Method[] methods = Clazz.getmethods ();
for (Method method:methods) {
If MethodInfo annotations exist on this method
if (Method.isannotationpresent (Methodinfo.class)) {
Get the MethodInfo annotations above
MethodInfo MethodInfo = method.getannotation (Methodinfo.class);
The Value property in the output annotation
System.out.println (Methodinfo.value ());
}
}
}
@org. junit.test
public void TestName () throws Exception {
Parse ();
}
}
Java Custom Annotation Implementation