执行以下方法时出现空指针异常。我已经调试,发现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 {


您还可以添加一个说@TargetCONSTRUCTOR,以使其只能出现在构造函数上。

10-07 23:43