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
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With