Reputation: 2078
I need to retrieve some annotated methods from various classes. I'm using this code:
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("my.package"))
.setScanners(new MethodAnnotationsScanner())
);
Set<Method> resources =
reflections.getMethodsAnnotatedWith(org.testng.annotations.Test.class);
I found the code for the Reflections class. However, this code is for the entire package
(and with that said, for some reason the code returns all annotated methods in my project, and not just the specified package).
However, I just want to get the annotated methods from one specific class. I can't make heads or tails of the Reflections javadoc.
How can I change the constructor so that only the annotated methods from a specific class are returned?
Upvotes: 1
Views: 2594
Reputation: 141
You're going to need to use an input filter to exclude other classes. Here's an example (note: if there are any classes nested within MyClass those will get matched as well.)
final String className = MyClass.class.getCanonicalName();
final Predicate<String> filter = new Predicate<String>() {
public boolean apply(String arg0) {
return arg0.startsWith(className);
}
};
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setUrls(ClasspathHelper.forClass(MyClass.class))
.filterInputsBy(filter)
.setScanners(new MethodAnnotationsScanner()));
Set<Method> resources =
reflections.getMethodsAnnotatedWith(org.testng.annotations.Test.class);
Upvotes: 4