7

Can I able to call a method which returns string inside an annotation.
If so please guide me how to achieve this?

I tried like this but this doesn't work for me.

@Description(value = Resource.getWord("key"))
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Clinton Prakash
  • 967
  • 9
  • 20

2 Answers2

6

An annotation only takes compile time constants (as they might be used during compile time), therefore you cannot make any calculation within the definition, as they are unknown during the compile time.

Allowed constant types are (taken from java-annotation-members):

  • Primitive
  • String
  • Class
  • Enum
  • Another Annotation
  • An array of any of the above

Possible solution for your situation:

As I understand you would like to localize the @Description content. As this is only meant to be exposed to other developers anyway, you are safe to simply use English, in my opinion. Localization is for the end user, not the developer.

Konrad
  • 355
  • 6
  • 18
Herr Derb
  • 4,977
  • 5
  • 34
  • 62
  • This is correct. To achieve what OP is trying to do, you can set the value you need at runtime via Reflection. You could store the method name and parameter in the Annotation, then replace some other value at runtime based on these attributes. – Strikegently Mar 14 '18 at 12:48
  • @Herr Derb Actually We need to display this content Resource.getWord("key") in client side. Is there any way to achieve this. – Clinton Prakash Mar 14 '18 at 13:09
  • @ClintonPrakash You can set the value `key` to the field of the annotation and then evaluate `Resource.getWord(annotation.getValue()) ` during runtime. – Herr Derb Jun 27 '18 at 11:55
  • If we have `@Retention(RUNTIME)` on the annotation, wouldn't this work for "non-compile-time" variable? – pavi2410 Jun 28 '19 at 12:37
0

I can imagine an aspect being wired up to process methods annotated like this, where the "key" is in the annotation, and the aspect processing then uses the key at run time... but I'm not sure this is what you're looking for.

Ben Ketteridge
  • 96
  • 2
  • 10