簡體   English   中英

使用用戶定義的注釋時獲取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");
        }
    }
}

默認情況下,注釋在運行時不可用。 您需要注釋您的注釋:P

@Retention(RetentionPolicy.RUNTIME)
@interface MyAssessment {

您還可以添加一個@Target CONSTRUCTOR以使其只出現在構造函數上。

您需要使用以下注釋來注釋您的注釋:

@Retention(RetentionPolicy.RUNTIME)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM