How to run all methods with a given annotation?

后端 未结 3 1533
说谎
说谎 2021-02-06 18:11

This is what I want to happen:

public class MainClass {
    public static void main(String args[]) { 
        run @mod(); // run all methods annotated with @mod          


        
3条回答
  •  别那么骄傲
    2021-02-06 18:42

    I think you can use reflection technique.

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface mod {
       public String name() default "";
    }
    
    public class Fundamental {
       public static void main(String[] args) {
          // Get all methods in order.
          // runClass is the class you declare all methods with annotations.
          Method[] methods = runClass.getMethods();
          for(Method mt : methods) {
            if (mt.isAnnotationPresent(mod.class)) {
                // Invoke method with appropriate arguments
                Object obj = mt.invoke(runClass, null);
            }
          } 
       }
    }
    

提交回复
热议问题