gpt4 book ai didi

java - 如何获取对象的所有字段和属性,这些字段和属性使用特定注释进行注释?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:14:13 24 4
gpt4 key购买 nike

如何在不遍历所有其字段或属性描述符的情况下获取对象(非类)的所有字段和属性?

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

或者迭代是唯一的出路吗?没有其他更好的方法吗?

最佳答案

您可以使用 reflections package那为你做了所有的工作。项目描述:

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:

  • get all subtypes of some type
  • get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
  • get all resources matching matching a regular expression

示例:

 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;
}
});

关于java - 如何获取对象的所有字段和属性,这些字段和属性使用特定注释进行注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com