Samuel Carrijo
Samuel Carrijo

Reputation: 17929

Avoiding a set of java annotations to be used together

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();
   ReasonToBeLarge reason(); //enum
   int estimatedTimeToRun();
}

Upvotes: 1

Views: 128

Answers (1)

Matt Ball
Matt Ball

Reputation: 359826

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")

Upvotes: 3

Related Questions