假设我有以下代码
URI uri = URI.create("https://example.com");
String myString = uri + "/something"; // why is this allowed and compiler doesnt complain?
我本以为编译器会抱怨向 URI 类型添加字符串
答案 0 :(得分:2)
JVM 调用对象的 toString() 方法。
答案 1 :(得分:1)
String myString = uri + "/something";
// why is this allowed and compiler doesnt complain?
Java中+
有两种含义:数字加法和字符串连接;见Assignment, Arithmetic, and Unary Operators。
如果其中一个或两个操作数表达式为String
,则采用字符串连接的含义。在这种情况下,other 操作数通过对其调用 toString()
被转换为字符串。因此...
String myString = uri + "/something";
表示几乎1与以下内容相同:
String myString = uri.toString().concat("/something");
1 - null
...