8

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(){
...
}
Shubham Randive
  • 128
  • 1
  • 9
  • What's the context? Where does the information have to come from? You can't use a class or local variable as argument to an annotation. – ernest_k Oct 30 '18 at 15:20
  • Maybe [this](https://stackoverflow.com/questions/2065937/how-to-supply-value-to-an-annotation-from-a-constant-java) answers your question? – Cortex0101 Oct 30 '18 at 15:22
  • In short: not, it's not possible. The annotation parameter values should be compile-time constants – Sergii Bishyr Oct 30 '18 at 15:22
  • Have you tried this? Were there errors? – Mark Oct 30 '18 at 15:22
  • duplicated: https://stackoverflow.com/questions/12568385/passing-dynamic-parameters-to-an-annotation – user3122166 Oct 30 '18 at 15:31
  • Does this answer your question? [Passing dynamic parameters to an annotation?](https://stackoverflow.com/questions/12568385/passing-dynamic-parameters-to-an-annotation) – EricSchaefer May 22 '21 at 10:55

1 Answers1

2

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)

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
9636Dev
  • 31
  • 3