2013-11-26 50 views
0

所以我在找的是如果有反正你可以讓一個@Annotation需要一個方法來有一個參數。如何在一個方法上需要一個參數有一個Annotation?

我的意思是,如果你有一個@Command的方法是需要方法的到有IssuedCommand

參數篩選

@Command public void command(IssuedCommand cmd) {} <它需要IssuedCommand在那裏,如果不會有錯誤。

反正這有可能嗎?

在此先感謝。

+0

在編譯時或運行時? –

+0

我希望它在運行時。 –

回答

0

下面是使用反射

public class Driver { 
    public static void main(String[] args) { 
     // get all methods 
     for (Method method : Driver.class.getDeclaredMethods()) { 
      // get your annotation 
      Annotation annotation = method.getAnnotation(Command.class); // reference could be of type Command if you want 
      if (annotation != null) { 
       // check if parameter exists 
       List<Class> parameterTypes = new ArrayList<Class>(Arrays.asList(method.getParameterTypes())); 
       if (!parameterTypes.contains(IssuedCommand.class)) { 
        System.out.println("trouble"); 
       } 
      } 
     } 
    } 

    @Command 
    public void command(IssuedCommand cmd) { 

    } 

    public static class IssuedCommand {} 

    @Retention(RetentionPolicy.RUNTIME) 
    @Target(value = ElementType.METHOD) 
    public @interface Command {} 
} 

您使用反射來得到你想要查詢的具體方法的工作示例。您可以通過檢查方法是否被註釋來做到這一點。然後可以比較方法參數列表中的類型。

相關問題