2

I see in Java when I use annotation to a method like this is not possible. It gives "Attribute must be a constant"

private static final String CONSTANT = MyClass.class.getCanonicalName();


@Timed(CONSTANT) //Attribute value must be constant
@CircuitBreaker(name = CONSTANT) //Attribute value must be constant
public String something( String something ) {

To emphasize, I am using @Timed and @CircuitBreaker here as example. Many other annotations will yield the exact same issue.

How to do it in Java? I mean, I do not want to hardcode the value here like such.

@Timed("MyClass") @CircuitBreaker(name = "MyClass")
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
PatPanda
  • 3,644
  • 9
  • 58
  • 154
  • Similar question: https://stackoverflow.com/q/3271659 . – Luke Woodward Oct 24 '20 at 11:30
  • Can you clarify your end goal? Your proximate problem is that you want two annotations to have the same argument. What is the reason you want to do that? (Also, I don't see that passing `CONSTANT` explicitly is any worse than writing `"MyClass"` explicitly.) – mernst Oct 25 '20 at 16:10
  • In this snippet, I showed 2, but actually, it is some 20 (but imagine a large number) spread among the entire class. If I need to change from MyClass to MyClazz (I know control + replace exists) changing one variable is always preferred to manually changing things in the code – PatPanda Oct 25 '20 at 21:40

1 Answers1

4
private static final String CONSTANT = MyClass.class.getCanonicalName();

These are the modifiers: private static final

This is the data-type/object-type: String

This is the name of your constant/variable/object: CONSTANT

This is the initiator: =

This is the attribute: MyClass.class.getCanonicalName();

Your attribute is not a constant, hence you can't initiate your constant CONSTANT.

paladin
  • 765
  • 6
  • 13