简体   繁体   中英

Converting a numeric constant to a constant string expression

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:

  • 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.

Define a new constant based on the first one of type String and use that one inside your annotation.

public static final int MAX_VALUE = 999;
public static final String MAX_VALUE_AS_STRING = String.valueOf(MAX_VALUE);

Then you can have the following, without duplicating the value of the max value:

@DefaultValue(PDCRuleMapping.MAX_VALUE_AS_STRING) final int upperBound;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM