避免一起使用的一组java注释

时间:2011-03-22 18:35:03

标签: java annotations

我创建了不同的java注释,不应该一起使用(类似@SmallTest@MediumTest@LargeTest。有没有办法让编译器不允许它们被使用一起?

编辑:更多信息使我的问题更加明确

假设我有:

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();
}

1 个答案:

答案 0 :(得分:3)

您可以创建一个带有枚举参数的注释,而不是创建三个不同的注释,例如@MyTest(TestSize.SMALL)@MyTest(TestSize.MEDIUM)@MyTest(TestSize.LARGE)

这样的事情(没有经过测试,没有保证,可能导致腹胀,yadda yadda):

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

编辑 re: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")
相关问题