4

我有以下Java代码 -

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);
        }

    }
}

我得到的错误是

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

如何正确访问注释字段?

4

1 回答 1

11

默认情况下,注释在运行时不可用。您需要添加@Retention(RetentionPolicy.RUNTIME)到注释定义中以使其可用于运行时处理。例如:

@Retention(RetentionPolicy.RUNTIME)
public @interface Size {

Field.isAnnotationPresent在实践中,您还应该在实际尝试从字段中获取注释之前检查该字段是否实际上具有给定的注释。

此外,用 . 指定注释所属的元素类型也是一个好习惯@Target。因此,您的示例将是:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Size {
于 2012-05-14T19:29:28.880 回答