[英]How to access fields defined in custom annotations in Java
我有以下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
如何正确访问注释字段?
默认情况下,注释在运行时不可用。 您需要将@Retention(RetentionPolicy.RUNTIME)
添加到注释定义中,以使其可用于运行时处理。 例如:
@Retention(RetentionPolicy.RUNTIME)
public @interface Size {
实际上,在实际尝试从该字段中获取注释之前,还应检查该字段是否实际上具有Field.isAnnotationPresent
的给定注释。
此外,使用@Target
指定注释所属的元素类型也是一种好习惯。 那你的例子就是:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Size {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.