Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中将编译时常量int转换为编译时常量字符串_Java_Type Conversion_Compile Time Constant - Fatal编程技术网

在Java中将编译时常量int转换为编译时常量字符串

在Java中将编译时常量int转换为编译时常量字符串,java,type-conversion,compile-time-constant,Java,Type Conversion,Compile Time Constant,我有一个需要编译时常量字符串的注释,我想用我正在使用的一个库中的编译时常量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.C

我有一个需要编译时常量字符串的注释,我想用我正在使用的一个库中的编译时常量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\u to_CONVERT
更好的方法将原语转换为编译时常量字符串?如何将原语“转换”为字符串?因为这样做感觉有点奇怪

尝试使用String.valueOf(LibraryClass.CONSTANT\u INT)

我建议

  • 使需要字符串的@Annotations取整数或
  • 将常量设为字符串。您可以在运行时将其解析为int
e、 g


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


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

但这不能直接在注释中使用,只能在常量字符串初始化中使用。是吗“私有静态最终字符串常量\u String=String.valueOf(LibraryClass.CONSTANT\u INT);“不适用?是的,这将是一个正确的答案。但我认为问题创建者要求的是类似@Annotations的东西,需要字符串(someCleverCastOf(CONSTANT_INT))。不,我必须自己更正。字符串不再是编译时常量,因此您的解决方案将不起作用-您不能在注释中使用常量。
public static int CONSTANT_INT = Integer.parseInt(CONSTANT_STRING);