CodeBlue CodeBlue - 1 year ago 63
Java Question

How to access fields defined in custom annotations in Java

I have the following Java code -

import java.lang.reflect.Field;

public class AnnotationTest
public @interface Size
int size();
int location();

@Size(size = 40, location = 85)
private String firstName;

@Size(size = 1, location = 21)
private String middleInitial;

@Size(size = 50, location = 115)
private String lastName;

public static void main(String[] args)
AnnotationTest t = new AnnotationTest();

Class<? extends AnnotationTest> classInstance = t.getClass();

for (Field f : classInstance.getDeclaredFields())
Size s = f.getAnnotation(Size.class);
int size = s.size(); // this is line 29
int location = s.location();

System.out.println("size = "+ size);
System.out.println("location = "+location);


The error I get is

Exception in thread "main" java.lang.NullPointerException
at com.stackoverflowx.AnnotationTest.main(

How to access the annotation fields correctly?

Answer Source

By default, annotations aren't available at runtime. You need to add @Retention(RetentionPolicy.RUNTIME) to your annotation definition to make it available for runtime processing. For example:

public @interface Size {

In practice, you should also check whether or not the field actually has a given annotation with Field.isAnnotationPresent before actually trying to get the annotation off of the field.

Also, it's also good practice to specify what types of elements your annotation belongs on with @Target. So your example would then be:

public @interface Size {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download