[英]Getting java.lang.NullPointerException while using user defined annotation
I am getting null pointer exception while executing following method. 执行以下方法时出现空指针异常。 I have debugged and found that
cons.getAnnotation(MyAssessment.class);
我已经调试并发现
cons.getAnnotation(MyAssessment.class);
is returning null
. 返回
null
。 Plese help 请帮助
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");
}
}
}
Annotations are not by default available at runtime. 默认情况下,注释在运行时不可用。 You need to annotate your annotation :P
您需要注释您的注释:P
@Retention(RetentionPolicy.RUNTIME)
@interface MyAssessment {
You can also add a @Target
of say CONSTRUCTOR
to say it should only appear on constructors. 您还可以添加一个
@Target
CONSTRUCTOR
以使其只出现在构造函数上。
您需要使用以下注释来注释您的注释:
@Retention(RetentionPolicy.RUNTIME)
You can change the Retention Policy of your annotation. 您可以更改注释的保留策略。 Using @Retention.
使用@Retention。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.