Good afternoon, ladies and gentlemen. Due to inexperience, I have this question. There is a code of my annotation, which is applied to the method in runtime:

@Target(value = ElementType.METHOD) @Retention(value = RetentionPolicy.RUNTIME) @interface CanRun{ int count(); } 

The question is, how can I make the annotation call the method as many times as will be specified in the count value?

  • You probably have a handler for this annotation? There it is necessary to do it. - Vartlok
  • Yes, there is a handler. There are just 4 methods. Before two there are annotations and call them in runtime. I understand how to do this, but I don’t understand how to use the count field for calls. - Mr.Inpus

2 answers 2

We take the annotation from the method and in the loop we call the method the necessary number of times. In the simplest example, it should be like this:

 Method method = myInstance.getClass().getMethod("methodName", methodParams); CanRun annotation = method.getAnnotation(CanRun.class); if (annotation != null) { int count = annotation.count(); for (int i = 0; i < count; i++) { method.invoke(myInstance, parameters); } } 

Where

myInstance - the object that will be searched for methods

methodParams - parameter classes

parameters - the list of parameters with which to run the method

  • Thanks for the answer, but tell me more please. If we specify a class of parameters, then the method turns out should accept them? - Mr.Inpus
  • if your method looks like this myMethod (java.uti.Date date, String s) then methodParams must be java.util.Date.class, String.class - Andrew Bystrov

A very simplified version, it can be taken as a basis for your case.

 public class Solution { public static void main(String[] args) throws Throwable { for (Method method : Solution.class.getDeclaredMethods()) { int count = 0; for (Annotation annotation : method.getDeclaredAnnotations()) if (annotation.annotationType() == Repeat.class) { count = method.getAnnotation(Repeat.class).count(); break; } for (int i = 0; i < count; i++) method.invoke(null); } } @Repeat(count = 10) public static void method() { System.out.println("hello world"); } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Repeat { int count() default 1; } } 
  • In this example, Annotation annotation, what's this annotation? - Mr.Inpus
  • no, this is such a class - Artem Konovalov