使用java注释和反射获取java.lang.NullPointerException

时间:2014-01-16 17:35:52

标签: java reflection nullpointerexception annotations

我写了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)

1 个答案:

答案 0 :(得分:5)

您需要@Retention运行时保留政策

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

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