An entity class in my application declares a numeric constant like
public static final int MAX_VALUE = 999;
This constant is already used in different parts of the application.
Now I would like to use this constant in a restful service in a parameter annotation. The problem is that the annotation @DefaultValue expects a string rather than an int. So I tried using String.valueOf
to get a string
@DefaultValue(String.valueOf(PDCRuleMapping.MAX_VALUE)) final int upperBound,
But it doesn't compile, because
The value for annotation attribute DefaultValue.value must be a constant expression
Can I reuse my numeric constant to get a constant string expression somehow, or do I have to write "999"
?
The only work around that worked for me so far is defining a String constant as follows:
public static final String MAX_VALUE_AS_STRING = "" + MAX_VALUE;
@DefaultValue(MAX_VALUE_AS_STRING) final int upperBound;
Alternatively, you can use string concatenation directly inside the annotation:
@DefaultValue("" + MAX_VALUE) final int upperBound;
Bear in mind that constant expressions, required in this context, do not allow method calls, only operators.
I think you only have two options:
@DefaultValue("999")
or declare a string constant:
public static final int MAX_VALUE = 999;
private static final String MAX_VALUE_STRING = "" + MAX_VALUE;
@DefaultValue(MAX_VALUE_STRING)
If the only place where you use that value in an annotation is in one class, you may want to declare the string constant private in that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With