开发者

Avoiding a set of java annotations to be used together

开发者 https://www.devze.com 2023-02-18 20:44 出处:网络
I have created different java annotations which shouldn\'t be used together (something like @SmallTest, @MediumTest and @LargeTest. Is there a way to make the compiler not allow them being used togeth

I have created different java annotations which shouldn't be used together (something like @SmallTest, @MediumTest and @LargeTest. Is there a way to make the compiler not allow them being used together?

EDIT: more info to make my problem more explicit

Suppose I have:

public @interface SmallTest
{
   String description();
}

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

public @interface LargeTest
{
   String description();
   ReasonToBeLa开发者_JAVA技巧rge reason(); //enum
   int estimatedTimeToRun();
}


Instead of creating three different annotations, you could create one annotation which takes an enum parameter, like @MyTest(TestSize.SMALL), @MyTest(TestSize.MEDIUM), or@MyTest(TestSize.LARGE).

Something like this (not tested, no guarantees, may cause abdominal distension, yadda yadda):

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

Edit re: OP's comment "What if the annotation has a content itself, say "description"? And what if the content for each is different (say one has description, the other has estimatedTimeToRun)?"

It's not fantastically elegant, but you could lump all of the annotation elements in as well, with reasonable defaults for the optional elements.

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

Then use it like:

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

精彩评论

暂无评论...
验证码 换一张
取 消