Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a numeric constant to a constant string expression

Tags:

java

constants

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"?

like image 309
iman00b Avatar asked Sep 11 '25 04:09

iman00b


2 Answers

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.

like image 132
Ahmad Shahwan Avatar answered Sep 13 '25 16:09

Ahmad Shahwan


I think you only have two options:

  • either use a string literal in the annotation @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.

like image 34
assylias Avatar answered Sep 13 '25 16:09

assylias