简体   繁体   中英

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); is returning 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

@Retention(RetentionPolicy.RUNTIME)
@interface MyAssessment {

You can also add a @Target of say CONSTRUCTOR to say it should only appear on constructors.

您需要使用以下注释来注释您的注释:

@Retention(RetentionPolicy.RUNTIME)

You can change the Retention Policy of your annotation. Using @Retention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM