这里用了自定义注解,不会的可以先去看看我这篇文章
怎么写注解https://blog.youkuaiyun.com/weixin_57604284/article/details/121420655?spm=1001.2014.3001.5501
方法 | 功能描述 |
---|---|
Annotation getAnnotation(Class annotyple) | 返回调用对象的注解 |
Annotation getAnnotations() | 返回调用对象的所有注解 |
Annotation getDeclareedAnnotations() | 返回调用对象的所有非继承注解 |
Boolean isAnnotationPresent(Class annotyple) | 判断调用对象关联的注解是由annoType指定的 |
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno1 {
String comment();
int order() default 1;
}
import java.lang.reflect.Method;
//使用自定义的@MyAnno1注解修饰类
@MyAnno1(comment = "类注解")
class MyClass1{
//使用自定义的@MyAnno1注解修饰方法
@MyAnno1(comment = "不带参数的方法", order = 2)
public void myMethod(){
}
}
public class MyAnno1Demo {
public static void main(String[] args) throws Exception{
//获取MyClass1类注解
MyAnno1 anno1 = MyClass1.class.getAnnotation(MyAnno1.class);
//输出类注解信息
System.out.println("MyClass类的注解信息为:" + anno1.comment() + ",序号" + anno1.order());
//获取MyClass1类的方法myMethod()方法
Method mth = MyClass1.class.getMethod("myMethod");
//获取myMethod()方法的注解
MyAnno1 anno2 = mth.getAnnotation(MyAnno1.class);
//输出方法注解的信息
System.out.println("myMethod()方法的注解信息为:" + anno2.comment() + ",序号" + anno2.order());
}
}
运行结果:
为了能使用反射机制获取注解的相关性息,在定义注解时必须将注解的保留策略设置为RetentionPolicy.RUNTIME,否则获取不到注解对象,程序将会引发NullPointerException空地址异常。