我编写了以下三个类“ PrintDevice,Printer,Test”,如下所示

首先,PrintDevice.java

public @interface PrintDevice{
    String defaultPrint();
    int defaultNumber();
}


二,Printer.java

@PrintDevice(defaultPrint="print",defaultNumber=5)
public class Printer{
    public Printer(){
        //empty Construcutor
    }
    @PrintDevice(defaultPrint="print",defaultNumber=5)
    public void print(int number){
        System.out.println(number);
    }
}


三,Test.java

import java.lang.reflect.*;
public class Test{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException{
        Printer printer = new Printer();
        PrintDevice anno = printer.getClass().getAnnotation(PrintDevice.class);
        Method m = printer.getClass().getMethod(anno.defaultPrint(),int.class);
        m.invoke(printer,anno.defaultNumber());
    }
}


并编译它们没有任何问题,但是当我尝试运行Test.java时,我得到了NullPointerExcetion,如下所示:


  线程“主”中的异常java.lang.NullPointerException
          在Test.main(Test.java:7)

最佳答案

您需要具有运行时保留策略的@Retention

@Retention(RetentionPolicy.RUNTIME)
public @interface PrintDevice{
    String defaultPrint();
    int defaultNumber();
}


否则,注释将在运行时不可用。

10-08 20:08