简体   繁体   中英

Get all methods with a particular annotation in a package

I know we can get all methods with a particular annotation inside a class. But I want all methods inside a package with that annotation. My use case : I want to annotate and identify few set of methods and ask my user to choose one of them add in a flow to execute.

@Retention(RetentionPolicy.RUNTIME)
@Target({ METHOD })
public @interface Step {
    String Type();// default "Trigger";
    String SubType();
    String [] tags();
}

public interface APITrigger {

    @Step(Type = "TRIGGER", SubType = "GET_CLASS_INSTANCE", tags = { "trigger", "build instance", "class object" })
    public Object getClassInstance(@NonNull final String packageNclassName)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, NoSuchFieldException;

    @Step(Type = "TRIGGER", SubType = "INVOKE_API_N_RETURN", tags = { "trigger", "hit api", "trigger api and return" })
    public Map<Class<?>, Object> invokeOveloadedAPINReturn(@NonNull final Object classInstance,
            @NonNull final String methodName);
}
public interface Comparator {

    @Step(Type = "COMPARATOR", SubType = "GENERIC_COMPARATOR", tags = { "compare", "expected", "observed", "any type", "generic comparator" })
    public <T> ComparisonResult Compare(T Expected, T Observed);

}

I want list of methods [getclassinstance, invokeOveloadedAPINReturn, Compare] as those three are annotated with Step. Can we do this with reflection? Also, can we restrict our search with variables inside annotation as well?

Best way is to use Reflections (this is name of this library) it allows for very simple scans of classpath to look for classes or methods with given annotations.

Set<Method> methodsAnnotatedWith = new Reflections("my.package", new MethodAnnotationsScanner()).getMethodsAnnotatedWith(SomeAnnotation.class);

If you want to write own one for some reason, then you need to get classpath and urls from given class loaders to manually scan for class files in given location to load them and check if they have given annotations/methods. This library also does that without loading classes you don't need, as scan itself is not loading classes, only classes that matches your "query" are loaded. (and it is doing that by loading .class files to own data structures)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM