![](/img/trans.png)
[英]Getting java.lang.NullPointerException with java annotation and reflection
[英]Getting java.lang.NullPointerException while using user defined annotation
执行以下方法时出现空指针异常。 我已经调试并发现cons.getAnnotation(MyAssessment.class);
返回null
。 请帮助
import java.lang.annotation.*;
import java.lang.reflect.*;
enum GradeLevel { POOR, AVERAGE, GOOD, VERYGOOD, EXTRAORDINARY }
@interface MyAssessment {
GradeLevel score();
}
public class Problem {
@MyAssessment(score=GradeLevel.GOOD)
public Problem(){
System.out.println("This is a constuructor");
}
public static void main(String... args){
try {
Class c = new Problem().getClass();
Constructor cons = c.getDeclaredConstructor();
MyAssessment an = (MyAssessment) cons.getAnnotation(MyAssessment.class);
System.out.println("YOUR SCORE IS : " + an.score());
}
catch(NoSuchMethodException nsme) {
System.out.println("Constructor thrown exception");
}
}
}
默认情况下,注释在运行时不可用。 您需要注释您的注释:P
@Retention(RetentionPolicy.RUNTIME)
@interface MyAssessment {
您还可以添加一个@Target
CONSTRUCTOR
以使其只出现在构造函数上。
您需要使用以下注释来注释您的注释:
@Retention(RetentionPolicy.RUNTIME)
您可以更改注释的保留策略。 使用@Retention。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.