我有以下 Java 类:
public class Test {
public static void main(String[] args) {
if (false) {
log("String_to_be_never_printed_1");
}
if (isPrintable()) {
log("String_to_be_never_printed_2");
}
}
private static boolean isPrintable() {
return false;
}
private static void log(String s) {
System.out.println(s);
}
}
在两个 if 语句中,结果均为 false。当我输出该类的常量池表时,我得到:
Constant pool:
#1 = Class #2 // Test
#2 = Utf8 Test
....
#18 = Utf8 isPrintable
#19 = Utf8 ()Z
#20 = String #21 // String_to_be_never_printed_2
#21 = Utf8 String_to_be_never_printed_2
#22 = Methodref #1.#23 // Test.log:(Ljava/lang/String;)V
#23 = NameAndType #24:#25 // log:(Ljava/lang/String;)V
...
当 String_to_be_never_printed_1 无处可见时,String_to_be_never_printed_2 出现(#20)。这是预期的,因为编译器优化了第一个 if 语句。
我的问题是虚拟机是否会设法从常量池中删除 String_to_be_never_printed_2 (因为这永远不会被使用)?
最佳答案
没有任何内容从常量池中删除。无论如何,这样做没有任何意义,因为删除不会对实际内存大小产生影响
关于Java 运行时常量池移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36894935/