import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.CLASS)
@interface MyAnno{
String str();
int val();
}
public class Meta {
@MyAnno(str ="Annotation Example",val=100)
public static void myMeth(){
Meta ob = new Meta();
try{
Class c = ob.getClass();
Method m = c.getMethod("myMeth");
MyAnno anno = m.getAnnotation(MyAnno.class );
System.out.println(anno.str()+" "+anno.val());
}catch (NoSuchMethodException exc){
System.out.println("Method not found");
}
}
public static void main(String[] args) {
myMeth();
}
}
当运行这个程序得到这个空指针异常,谁能解释为什么和如何捕获这个异常,并最终修复这个代码?
Exception in thread "main" java.lang.NullPointerException
at Meta.myMeth(Meta.java:19)
at Meta.main(Meta.java:25)
您还需要在运行时保留注释。当您指定RetentionPolicy.CLASS
时,这并不像文档所说的那样:
注释将被编译器记录在类文件中
不需要在运行时被虚拟机保留
所以改成@Retention(RetentionPolicy.RUNTIME)
虚拟机运行时不保留CLASS
RetentionPolicy
。你可以使用
@Retention(RetentionPolicy.RUNTIME)