我有以下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
如何正确访问注释字段?