如何访问Java中自定义注释中定义的字段 [英] How to access fields defined in custom annotations in Java

查看:320
本文介绍了如何访问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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆