Find method from annotation

2019-08-31 15:30发布

问题:

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?

回答1:

Find all the methods annotated with @Named with the argument Qty, then look for a method named getQty, or from the list of annotated methods, check for the getter prefix.



回答2:

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.



回答3:

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.

Named attr = method . getAnnotation ( Named . class ) ;
if ( ( attr != null ) && ( attr . value == "Qty" ) ) ...


回答4:

using the Reflections library, you can do something like this:

Reflections reflections = new Reflections("my.package", new MethodAnnotationsScanner());
Set<Method> namedMethods = reflections.getMethodsAnnotatedWith(Names.class);
//or even
Set<Method> qtyMethods = reflections.getMethodsAnnotatedWith(
        new Named() {
            public String value() { return "Qty"; } 
            public Class<? extends Annotation> annotationType() { return Named.class; }
        });

Then, it's easy to get just the setter methods using conventional java reflection, although Reflections can also help you here:

import static org.reflections.ReflectionsUtils.*;
Set<Method> setterMethods = getAll(methods, withPrefix("set"));