annotations with varargs parameters

say I have an annotation called @Person. I give it two attributes “name” and “address”. Definition

public @interface Person {

String name();

String address();

}

To use I must now do @Person(name=”bob”, address=”home”)

And what if just want the name? definition becomes

public @interface Person {

String value();

}

Now I can do @Person(“bob”). The magic is to have just one attribute and name it “value”. Anything other than value and it has to include the attribute name in the use.

Of course we can also define default values so to have address too but optional

public @interface Person {

String value();

String address() default “home”;

}

Now we can still do @Person(“bob”) and the annotation will have the values value=”bob”, address=”home”. Or you can do @Person(value=”bob”, address=”other”) but note that value is no longer sufficient. Of course, I have to admit I do not know if you can just do @Person(“bob”) if you have more than one attribute but with default values. But lets guess so and not test it, right? Famouse last wordsies…

Example2:

public @interface RelatedTo {

String value() default “all”;

}

We can use this like @RelatedTo(“bob”) or with just @RelatedTo. The first relates to “bob”, the second to “all”.

But assume we want to be able to give more than one String as parameter but only one or none if we wish to. So we could do any of these

@RelatedTo

@RelatedTo(“bob”)

@RelatedTo({“bob”, “alice”})

It seems like varargs could solve this for us. But since annotations fail to compile if we define

public @interface RelatedTo {

String… value() default “all”;

}

That does not work. But strangely enough this does

public @interface RelatedTo {

String[] value() default “all”;

}

And so we can define all the three annotations given above with this definition.

whooppee

1 thought on “annotations with varargs parameters

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s