Parisbre56
Parisbre56

Reputation: 157

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.

Upvotes: 1

Views: 471

Answers (3)

Florian Albrecht
Florian Albrecht

Reputation: 2326

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?).

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

I would suggest

  • make @AnnotationThatNeedsString take an int or
  • make the constant a String. You can parse it as an int at runtime.

e.g.

public static int CONSTANT_INT = Integer.parseInt(CONSTANT_STRING);

Upvotes: 0

Anthony
Anthony

Reputation: 116

Try using String.valueOf(LibraryClass.CONSTANT_INT);

Upvotes: 0

Related Questions