Reputation: 157
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
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
Reputation: 533492
I would suggest
e.g.
public static int CONSTANT_INT = Integer.parseInt(CONSTANT_STRING);
Upvotes: 0