使用用户定义的注释时获取 java.lang.NullPointerException

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");
        }
    }
}

您需要为您的注释添加注释:

@Retention(RetentionPolicy.RUNTIME)

默认情况下,注释在运行时不可用。您需要注释您的注释:P

@Retention(RetentionPolicy.RUNTIME)
@interface MyAssessment {

您还可以添加一个 @Target of say CONSTRUCTOR 来说明它应该只出现在构造函数中。

您可以更改注释的保留策略。使用@Retention.