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(Demo.java:125
How to access the annotation fields correctly?
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:
@Retention(RetentionPolicy.RUNTIME)
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:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Size {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With