I am looking at some code where class level annotations are used to ‘add’ properties to certain classes, later using reflection these properties are accessed and used.
My question:
When is it appropriate to use an annotation to add new fields to a class, instead of using an interface. What are some benefits and drawbacks to this?
I don’t know that annotations would ever replace an interface, but I can kind of see the allure. It all depends on the implementations though.
Annotations provide meta data to further describe code, which a consumer (most of the time) interprets at runtime using reflections. Using an interface, this contract of implementation is clearly defined.
You could have:
This would be a cumbersome contract to implement, and would likely incur some sort of method chaining.
Instead you could do something like:
The drawback is that it would be cumbersome to use:
Annotations in this example would be overkill a majority of the time, IMO. There is something to be said about a clearly defined, well documented contract.