how to create a single annotation accept multiple values in Java

Junchen Liu picture Junchen Liu · Sep 28, 2012 · Viewed 13.9k times · Source

I have a Annotation called

@Retention( RetentionPolicy.SOURCE )
@Target( ElementType.METHOD )
public @interface JIRA
{
    /**
     * The 'Key' (Bug number / JIRA reference) attribute of the JIRA issue.
     */
    String key();
}

which allows to add annotation like this

@JIRA( key = "JIRA1" )

is there any way to allow this to happen

@JIRA( key = "JIRA1", "JIRA2", .....  )

the reason is, we currently annotate the test against a Jira task or bug fix, but sometimes, then the value will get parsed by sonar. problem is a single test covers more then 1 bug.

Answer

Amit Deshpande picture Amit Deshpande · Sep 28, 2012

Change your key() function to return String[] rather than String then you can pass various values using String[]

public @interface JIRA {
/**
 * The 'Key' (Bug number / JIRA reference) attribute of the JIRA issue.
 */
String[] key();
}

Use it like below

@JIRA(key = {"JIRA1", "JIRA2"})