2011-03-22 38 views
0

我創建了不應該一起使用的不同的java註釋(類似@SmallTest,@MediumTest@LargeTest。有沒有辦法讓編譯器不允許它們一起使用?避免一組java註釋一起使用

編輯:更多信息,使我的問題更加明確

假設我有:

public @interface SmallTest 
{ 
    String description(); 
} 

public @interface MediumTest 
{ 
    String description(); 
    ReasonToBeMedium reason(); //enum 
    int estimatedTimeToRun(); 
} 

public @interface LargeTest 
{ 
    String description(); 
    ReasonToBeLarge reason(); //enum 
    int estimatedTimeToRun(); 
} 

回答

3

而不是創建三個不同的註解,你可以創建e註釋採用枚舉參數,如@MyTest(TestSize.SMALL)@MyTest(TestSize.MEDIUM)@MyTest(TestSize.LARGE)

像這樣的東西(未測試,沒有保證,可能會引起腹脹,內容非常重要):

public @interface MyTest 
{ 
    TestSize value() default TestSize.MEDIUM; 
} 

編輯回覆:OP的評論「如果標註有內容本身,說「描述」?如果每個內容不同(說一個有描述,另一個估計了TimeToRun)?

這不是非常優雅,但是你也可以包含所有的註解元素,並且可選的元素有合理的默認值。

public @interface MyTest 
{ 
    String description();     // required 
    TestSize size() default TestSize.MEDIUM; // optional 
    long estimatedTimeToRun default 1000; // optional 
} 

然後使用它像:

  • @MyTest(description="A big test!")
  • @MyTest(size=TestSize.SMALL, description="A teeny tiny test", estimatedTimeToRun = 10)
  • @MyTest(description="A ho-hum test")
+0

如果標註有內容本身,說 「說明」?如果每個內容不同(比如說有一個描述,另一個估計了TimeToRun)? – 2011-03-22 18:48:15

+0

@Samuel看到我的編輯。 – 2011-03-22 18:55:50

+0

最後一個問題。如果他們有特定的屬性,如枚舉ReasonToBeLarge,枚舉ReasonToBeMedium和類似的東西呢?有沒有辦法讓他們分開? – 2011-03-22 20:01:27