Java编译器字符串优化

use*_*607 6 java compiler-construction string

对我来说,编译器会采用这样的方式似乎是合理的:

log.info("A really long logger message that is kind of a pain in the tucous " + 
    "and violates formatting standards by making the line to long");
Run Code Online (Sandbox Code Playgroud)

并将两个字符串编译成一个.我很确定这是真的,但如果有人提出来的话,我想把我的鸭子连成两排.

Jef*_*ter 10

是的,这将由Java语言规范的常量表达式部分处理.特别参见第15.18.1部分.字符串连接运算符+


Per*_*ion 7

由常量表达式计算的字符串(第15.28节)在编译时计算,然后将其视为文字.

JLS的引用显示给任何"挑战"你的人.


Evg*_*eev 3

为了检查 JLS 关于常量表达式的说法是否正确,我编译了这段代码,Test.java

public static void main(String[] args) {
    log.warning("123" + "456");
}
Run Code Online (Sandbox Code Playgroud)

然后用 Jad 反编译 Test.class 并得到这个

public static void main(String args[])
{
    log.warning("123456");
}
Run Code Online (Sandbox Code Playgroud)

也就是说,在 Test.class 中只有一个文字“123456”