【发布时间】:2026-01-06 19:05:01
【问题描述】:
我刚刚发现了这行奇怪的代码,它可以编译:
String a = (new File("")) + "f";
System.out.println(a);
输出:
f
我在 Windows 10 Pro 上的 Eclipse Neon.2 上使用 jre 1.8_111。
它只用一个空的 String 初始化程序编译,但我认为它不应该,因为 + 运算符没有为 File 重载。还是这样?
我检查了new File("") 不是null,但它的filePath 和status 是。
任何想法为什么它编译?
【问题讨论】:
-
你也可以用字符串连接对象。在内部将调用
.toString()方法。 -
你可以用字符串连接任何东西。这就是
toString()的用途。