获取与注释字段列表,利用反射 [英] Get list of fields with annotation, by using reflection

查看:84
本文介绍了获取与注释字段列表,利用反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建我的注释

public @interface MyAnnotation {
}

我把它放在场在我的测试对象

I put it on fields in my test object

public class TestObject {

    @MyAnnotation 
    final private Outlook outlook;
    @MyAnnotation 
    final private Temperature temperature;
     ...
}

现在我想要得到的所有字段列表以 MyAnnotation

Now I want to get list of all fields with MyAnnotation.

for(Field field  : TestObject.class.getDeclaredFields())
{
    if (field.isAnnotationPresent(MyAnnotation.class))
        {
              //do action
        }
}

但好像我做块从不执行行动和领域没有任何标注如下code返回0。

But seems like my block do action is never executed, and fields has no annotation as the following code returns 0.

TestObject.class.getDeclaredField("outlook").getAnnotations().length;

是任何人都可以帮助我,告诉我什么,我做错了什么?

Is anyone can help me and tell me what i'm doing wrong?

推荐答案

您需要标记注释为是在运行时可用。以下添加到您的注释code。

You need to mark the annotation as being available at runtime. Add the following to your annotation code.

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}

这篇关于获取与注释字段列表,利用反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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