在 Java 中将编译时常量 int 转换为编译时常量 String

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

我有一个注释需要一个编译时常量字符串,我想用我正在使用的库之一的编译时常量 int 来初始化它。所以我最终做的是这样的:

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
    }
}

我的问题是,是否有比使用 "" + PRIMITIVE_TO_CONVERT 更好的方法将原语转换为编译时常量字符串? "cast" 原始字符串的某种方式?因为这样做感觉有点奇怪。

尝试使用 String.valueOf(LibraryClass.CONSTANT_INT);

我会建议

  • 使@AnnotationThatNeedsString 接受一个整数或
  • 使常量成为字符串。您可以在运行时将其解析为 int。

例如

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

我认为您当前的解决方案是最好的,因为您正确地确定注释需要 "compile-time constant" 值。 "" + INT_VALUE 至少比通过重复库中的值来创建冗余要好,但是作为一个字符串 ("23"),它是 Java 语言的一个 "nice" 特性将您的解决方案确定为编译时常量。

如果可以的话,您当然也可以按照另一个答案中的建议更改 Annotation 以将 int 作为值参数(但我假设 Annotation 也来自库?)。