I have, thanks to @Robert Knock's indication, found a solution to my problem. I am posting my answer for future reference.
So Say we have the following package annots_package
and the following annotation:
package annots_package;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface ToSelect {
boolean selectable();
}
With the following class that has the method to select other methods:
package annots_package;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class Main {
public static ArrayList<Method> selectedMethods = new ArrayList<Method>();
public Main() {
System.out.println("Instanciated Main");
}
@ToSelect(selectable = false)
public static void main(String[] args) throws Exception {
Class<?> c = Class.forName("annots_package.Main");
Method[] methods = c.getDeclaredMethods();
for(Method method : methods) {
ToSelect annotation = method.getAnnotation(ToSelect.class);
if(annotation != null) {
boolean selectable = annotation.selectable();
if (selectable) {
selectedMethods.add(method);
}
}
}
for(Method method : selectedMethods) {
System.out.println(method.toString());
}
}
@ToSelect(selectable = true)
public void method_1() {
System.out.println("method_1");
}
@ToSelect(selectable = false)
public void method_2() {
System.out.println("method_2");
}
@ToSelect(selectable = true)
public void method_3() {
System.out.println("method_3");
}
}
So in order for me to select only method_1()
and method_3()
which are annotated @ToSelect(selectable = true)
, I first made a list of all the methods the class has, then created an annotation for each method, next, I checked if annotation is not null (since the method main()
has no annotation, it could throw a NullPointerException
) so this way, I avoided that. And only then I checked if the selectable()
attribute of the annotation is true
(could be something else). This way I made my ArrayList of methods I am interested in.
Thanks everyone.