Search code examples
javatype-conversioncompile-time-constant

Convert compile-time-constant int to compile-time-constant String in Java


I have an annotation that requires a compile-time-constant String and I wanted to initialize it with a compile-time-constant int from one of the libraries I'm using. So what I ended up doing was something like this:

public class LibraryClass {
    public static int CONSTANT_INT = 0; //Where 0 could be whatever
}

public class MyClass {
    private static final String CONSTANT_STRING = "" + LibraryClass.CONSTANT_INT;

    @AnnotationThatNeedsString(CONSTANT_STRING)
    public void myMethod() {
        //Do something
    }
}

My question is, is there a better way of converting primitives to compile-time-constant Strings than using "" + PRIMITIVE_TO_CONVERT? Some way to "cast" a primitive to String? Because doing it like this feels a bit weird.


Solution

  • I think your current solution is best, as you correctly determined that Annotations need "compile-time constant" values. "" + INT_VALUE is at least better than creating redundancy by repeating the value from the library, but as a String ("23"), and it's a "nice" feature of the Java language to determine your solution as compile-time constant.

    If you are able to, you could of course also change the Annotation to take an int as value parameter, as suggested in another answer (but I assume the Annotation comes from a library as well?).