Scorpion
Scorpion

Reputation: 587

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)

Upvotes: 0

Views: 1156

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280141

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.

Upvotes: 5

Related Questions