如何获取使用特定注释注释的对象的所有字段和属性? [英] How do I get all fields and properties of an object that are annotated with specific annotation?

查看:103
本文介绍了如何获取使用特定注释注释的对象的所有字段和属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不遍历所有其字段或属性描述符的情况下获取使用特定注释进行注释的对象(而非类)的所有字段和属性?

How do I get all the fields and properties of an object (not class) that are annotated with specific annotation without iterating through all its fields or property descriptors?

我的目标是避免对每个明显甚至没有注释的字段或属性进行不必要的迭代,例如 getClass() 或类的任何不是实例的字段或成员变量的字段.

My objective is to avoid unnecessary iteration through each and every field or property that is obviously not even annotated such as getClass() or any field of the class that is not a field or member variable of an instance.

或者迭代是唯一的出路?有没有其他更好的方法来做到这一点?

Or is iteration the only way to go? Is there no other better way of doing this?

推荐答案

您可以使用 reflections 包为您完成所有工作.项目说明:

You could use the reflections package that does all the work for you. The description of the project:

反射扫描你的类路径,索引元数据,允许你在运行时查询它,并可以保存和收集项目中许多模块的信息.

Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.

使用反射,您可以查询您的元数据,例如:

Using Reflections you can query your metadata such as:

  • 获取某种类型的所有子类型
  • 获取所有类型/方法/字段用一些注释进行注释,不匹配注释参数
  • 获取匹配正则表达式的所有资源

<小时>

示例:

 Reflections reflections = new Reflections("my.project.prefix");

 Set<Class<? extends SomeType>> subTypes = 
           reflections.getSubTypesOf(SomeType.class);

 Set<Class<?>> annotated = 
           reflections.getTypesAnnotatedWith(SomeAnnotation.class);

 Set<Class<?>> annotated1 =
           reflections.getTypesAnnotatedWith(new SomeAnnotation() {
                public String value() { return "1"; }
                public Class<? extends Annotation> annotationType() { 
                    return SomeAnnotation.class; 
                }
            });

这篇关于如何获取使用特定注释注释的对象的所有字段和属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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