如何访问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 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 {