简体   繁体   中英

How do I get all fields and properties of an object that are annotated with specific annotation?

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?

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?

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:

  • 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

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM