Shubham Randive
Shubham Randive

Reputation: 138

pass variable as annotation parameter

I am using annotation in my java program something like this.

@annotation("some string")
public void fun(){
...
} 

Is there any way that i could pass variable instead of "some string" to annotation.

e.g

String s="some string"
@annotation(s)
public void fun(){
...
}

Upvotes: 8

Views: 12758

Answers (1)

9636Dev
9636Dev

Reputation: 41

It is not possible to give an annotation a changing variable. The value which is passed in to the annotation needs to be known at compile time.

This would work:

private final String param = "Param";

@annotation(param)
public void function() {

}

However, it must be constant and cannot be changed, e.g. intialized by the constructor. (The value in this case would be known at runtime, not compile time)

Upvotes: 3

Related Questions