我写了3个类“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如下: -
线程“main”java.lang.NullPointerException中的异常 在Test.main(Test.java:7)
答案 0 :(得分:5)
您需要@Retention
运行时保留政策
@Retention(RetentionPolicy.RUNTIME)
public @interface PrintDevice{
String defaultPrint();
int defaultNumber();
}
否则注释在运行时不可用。