简体   繁体   中英

Getting java.lang.NullPointerException with java annotation and reflection

I wrote 3 classes "PrintDevice, Printer, Test" as follow

First, PrintDevice.java

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

Second, 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);
    }
}

Third, 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());
    }
}

and compile them without any problem, but when I attempt to run the Test.java ,I got NullPointerExcetion as follows:-

Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:7)

You need @Retention with a run time retention policy

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

otherwise the annotation is not available at run time.

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