David Guo
David Guo

Reputation: 1759

java Annotation reflection

I have a java class, for some field (not all field), I will put an annotation for the filed. Now, I would like to find all the fields which have annotation?

I know, I can iterate all fields, and find whether the field has annotation. Since there is only one or two field has annotation, so I would like a quick method to find such annotated field.

Upvotes: 3

Views: 524

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503090

I don't know any way quicker than iterating over all the fields. Given that anything else would require some other piece of code to iterate over all the fields first and store the annotations in a form more optimized for your use case - which certainly won't be useful for all annotations - I wouldn't expect there to be anything provided for you.

Have you benchmarked the speed of just iterating over the fields, and found it too slow? If you only need to do this occasionally, it's probably fast enough as it is. If you need to do it multiple times on the same class, then you can create a cache for this yourself, so you only ever need to iterate over the fields of any particular class once.

Upvotes: 5

Related Questions