Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(Demo.java:125

How to access the annotation fields correctly?

like image 564
CodeBlue Avatar asked Dec 20 '22 21:12

CodeBlue


1 Answers

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 {
like image 135
Tim Pote Avatar answered Jan 13 '23 15:01

Tim Pote