gpt4 book ai didi

java - 如果可以在编译时确定 Java 是否保证内联字符串常量

转载 作者:太空狗 更新时间:2023-10-29 22:32:49 27 4
gpt4 key购买 nike

考虑这种情况:

public Class1 {
public static final String ONE = "ABC";
public static final String TWO = "DEF";
}

public Class2 {

public void someMethod() {
System.out.println(Class1.ONE + Class1.TWO);
}
}

通常您会希望编译器内联 ONE 和 TWO 常量。但是,这种行为有保证吗?您能否在类路径中没有 Class1 的情况下在运行时部署 Class2,并期望它在任何编译器下都能正常工作,或者这是一个可选的编译器优化?

编辑:到底为什么要这样做?好吧,我有一个常量可以在应用程序的两端(通过 RMI 的客户端和服务器)共享,在这种特殊情况下,将常量放在只能位于该分界线一侧的类上会非常方便(因为它在逻辑上是拥有该常量值的那个)而不是仅仅因为它需要由代码的双方共享而将其放在任意常量类中。在编译时它都是一组源文件,但在构建时它是按包划分的。

最佳答案

它保证被视为常量表达式,并保证被section 15.28 of the JLS 实习。 :

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • Literals of primitive type and literals of type String (§3.10.5)
  • Casts to primitive types and casts to type String
  • The unary operators +, -, ~, and ! (but not ++ or --)
  • The multiplicative operators *, /, and %
  • The additive operators + and -
  • ...

...

Compile-time constants of type String are always "interned" so as to share unique instances, using the method String.intern.

现在,这并不能完全保证内联。但是,规范的第 13.1 节说:

References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted. No reference to such a constant field should be present in the code in a binary file (except in the class or interface containing the constant field, which will have code to initialize it), and such constant fields must always appear to have been initialized; the default initial value for the type of such a field must never be observed.

换句话说,即使表达式本身不是常量,也不应该引用 Class1。所以是的,你没事。这并不必然保证在字节码中使用连接值,但前面引用的位保证连接值被保留,所以我非常感到惊讶如果它不只是内联连接值。即使没有,您也可以保证它在没有 Class1 的情况下也能正常工作。

关于java - 如果可以在编译时确定 Java 是否保证内联字符串常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406616/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com