Damien-Amen
Damien-Amen

Reputation: 7502

Passing a method in an annotation

I created an annotation like below

@Retention(RetentionPolicy.RUNTIME)
public @interface TestData
{
String[] values();

}

I use it in my class like below

@TestData({"test1","test2","test3"})

public void testMethod(String data) {
   //Some code here
}

What I'd like to do is.. For the TestData annotation I'd like to dynamically generate a few values and pass it on. For Eg:

Let's say I have a method called getData();

public string[] getData() {
   //Code to return an array
   return array[];
}

Now I want to be able to pass the values of getData() method to my @TestData annotation. Is that possible?

Upvotes: 2

Views: 291

Answers (1)

Jesper
Jesper

Reputation: 206816

No, that is not possible, the values that are on the annotation have to be known at compile time, so you cannot use the result of a method, because that won't be known until you run the program.

This is explained in JLS 9.7.1 (the description of the ElementValue, V). This paragraph says:

  • if the type is primitive or String it must be a constant expression (i.e. a compile-time constant)
  • if the type is Class it must be a class literal
  • if the type is an enum it must be an enum constant
  • if the type is an array then the above rules are applicable to the array elements

The return value of a method is not a compile-time constant.

Upvotes: 1

Related Questions