如何访问 Java 中自定义注释中定义的字段 [英] How to access fields defined in custom annotations in Java
问题描述
我有以下 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);
}
}
}
我得到的错误是
Exception in thread "main" java.lang.NullPointerException
at com.stackoverflowx.AnnotationTest.main(Demo.java:125
如何正确访问注解字段?
How to access the annotation fields correctly?
推荐答案
默认情况下,注释在运行时不可用.您需要将 @Retention(RetentionPolicy.RUNTIME)
添加到您的注释定义中,使其可用于运行时处理.例如:
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 {
在实践中,在实际尝试从字段中获取注释之前,您还应该使用 Field.isAnnotationPresent
检查该字段是否确实具有给定的注释.
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.
此外,使用 @Target
指定注释所属的元素类型也是一种很好的做法.所以你的例子是:
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 {
这篇关于如何访问 Java 中自定义注释中定义的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!