Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a single annotation accept multiple values in Java

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.

like image 899
Junchen Liu Avatar asked Sep 28 '12 09:09

Junchen Liu


People also ask

Can you apply more than one annotation?

It is now possible to use an annotation zero times, once, or, if the annotation's type is marked as @Repeatable , more than once. It is also possible to restrict where an annotation type can be used by using the @Target meta-annotation.

Can you apply more than one annotation on any method in Java?

In Java 8 (released in March 2014), it is possible to write repeated/duplicate annotations.

Can we apply two annotations together?

It is also possible to use multiple annotations on the same declaration: @Author(name = "Jane Doe") @EBook class MyClass { ... } If the annotations have the same type, then this is called a repeating annotation: @Author(name = "Jane Doe") @Author(name = "John Smith") class MyClass { ... }

What is the use of annotation in Java?

Java annotations are metadata (data about data) for our program source code. They provide additional information about the program to the compiler but are not part of the program itself. These annotations do not affect the execution of the compiled program.


1 Answers

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"})
like image 116
Amit Deshpande Avatar answered Oct 06 '22 22:10

Amit Deshpande