Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 259
supertonsky Avatar asked Dec 14 '12 08:12

supertonsky


1 Answers

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; 
                }
            });
like image 73
dacwe Avatar answered Sep 22 '22 16:09

dacwe