I\'m attempting to slap two or more annotations of the same type on a single element, in this case, a method. Here\'s the approximate code that I\'m working with:
If you have only 1 parameter "bar" you can name it as "value". In this case you wont have to write the parameter name at all when you use it like this:
@Foos({@Foo("one"), @Foo("two")})
public void haha() {}
a bit shorter and neater, imho..
combining the other answers into the simplest form ... an annotation with a simple list of values ...
@Foos({"one","two"})
private String awk;
//...
public @interface Foos{
String[] value();
}
Apart from the other ways mentioned, there is one more less verbose way in Java8:
@Target(ElementType.TYPE)
@Repeatable(FooContainer.class)
@Retention(RetentionPolicy.RUNTIME)
@interface Foo {
String value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface FooContainer {
Foo[] value();
}
@Foo("1") @Foo("2") @Foo("3")
class Example{
}
Example by default gets, FooContainer
as an Annotation
Arrays.stream(Example.class.getDeclaredAnnotations()).forEach(System.out::println);
System.out.println(Example.class.getAnnotation(FooContainer.class));
Both the above print:
@com.FooContainer(value=[@com.Foo(value=1), @com.Foo(value=2), @com.Foo(value=3)])
@com.FooContainer(value=[@com.Foo(value=1), @com.Foo(value=2), @com.Foo(value=3)])
In Java 8 (released in March 2014), it is possible to write repeated/duplicate annotations.
See tutorial, Repeating Annotations.
See specification, JEP 120: Repeating Annotations.
http://docs.oracle.com/javase/tutorial/java/annotations/repeating.html
Starting from Java8 you can describe repeatable annotations:
@Repeatable(FooValues.class)
public @interface Foo {
String bar();
}
public @interface FooValues {
Foo[] value();
}
Note, value
is required field for values list.
Now you can use annotations repeating them instead of filling the array:
@Foo(bar="one")
@Foo(bar="two")
public void haha() {}
In the current version of Java, I was able to resolve this issue with the following annotation:
@Foo({"one", "two"})