实现自定义注解
自定义注解:
示例:
package com.yjy.work;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 将这个注解标注为只能放在方法上
@Target(ElementType.METHOD)
// 用于指定一条注解应该保留多长时间 RetentionPolicy.RUNTIME表示包括在类文件中的注解,并由虚拟机载入。通过反射API可获得它们
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
enum Status {UNCONFIRMED, CONFIRMED, FIXED, NOTABUG;};
String name() default "myAnnotation";
Status status() default Status.UNCONFIRMED;
String test();
}
使用注解:
获取注解信息
示例:
package com.yjy.work;
import jdk.nashorn.internal.ir.annotations.Reference;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Test {
@Reference
@MyAnnotation(test = "123")
public void myTest() {
}
public static void main(String[] args) throws NoSuchMethodException {
Class<? extends Test> aClass = new Test().getClass();
Method myTest = aClass.getMethod("myTest");
MyAnnotation annotation = myTest.getAnnotation(MyAnnotation.class);
System.out.println(annotation);
System.out.println(myTest.isAnnotationPresent(MyAnnotation.class));
Annotation[] annotations = myTest.getAnnotations();
for (Annotation annotation1 : annotations) {
System.out.println(annotation1);
}
}
}