
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空地址异常。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)