3

これが私がしたいことです:

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

注釈宣言:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface mod {
   String name() default "";
}

呼び出されるメソッド:

public class Good {
    @mod (name = "me1")
    public void calledcs(){
        System.out.println("called");
    }

    @mod (name = "me2")
    public void calledcs2(){
        System.out.println("called");
    }
}

または同じことを達成する別の方法はありますか?

4

3 に答える 3

3

リフレクションテクニックが使えると思います。

@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);
        }
      } 
   }
}
于 2013-06-09T03:34:34.737 に答える