It is possible in Java to find a method from its annotations? For instance:
@Named("Qty")
public getQty()
{
return _quantity;
}
@Named("Qty")
public void setQty(long qty)
{
_quantity = qty;
}
I know that both are annotated as "Qty", how can retrieve the setter method for example on runtime?
You can use reflection.
Use Class and Method to iterate over the methods. Use the getAnnotation method to determine if a method has the annotation.
Find all the methods annotated with
@Named
with the argumentQty
, then look for a method namedgetQty
, or from the list of annotated methods, check for the getter prefix.using the Reflections library, you can do something like this:
Then, it's easy to get just the setter methods using conventional java reflection, although Reflections can also help you here:
It is costly, first use on the Class getDeclaredMethods, for the Method get its Named annotation and then inspect the method name for "get[A-Z]" or "is[A-Z]". Better to tackle the problem in some other manner.