1

Not sure what I'm doing wrong here. My objective is to get the annotation of a method (if exists).

public class RunTest
{
public static void main(String[] args) throws Exception, NoSuchMethodException
{
    MyAction action = new MyAction(); 

    Method method = action.getClass().getDeclaredMethod("printSomething");

    RequiredPermission permission = method.getAnnotation(RequiredPermission.class);
    String value = permission.permissionName();

    System.out.println("permission name: "+value);

}
}

MyAction class

public class MyAction
{
@RequiredPermission(permissionName="SYSO", permissionValue = 0)
public void printSomething()
{
    System.out.println("hi there");
}

public void printABC()
{
    System.out.println("ABC...");
}
}

and the annotation:

public @interface RequiredPermission
{
    String permissionName();
    int permissionValue();
}

I would expect to see on the console:

permission name: SYSO

but instead I get:

Exception in thread "main" java.lang.NullPointerException at com.annotation.RunTest.main(RunTest.java:14)

adhg
  • 10,437
  • 12
  • 58
  • 94

2 Answers2

6

The annotation must have its Retention Policy set to RUNTIME in order to access it via reflection.

Add the following to your annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredPermission
{
    String permissionName();
    int permissionValue();
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
3

You probably forgot to specify RUNTIME as the RetentionPolicy of your annotation.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255