为什么向 Object 添加字符串会将类型更改为字符串?

时间:2021-04-04 00:30:35

标签: java

假设我有以下代码

URI uri = URI.create("https://example.com");

String myString = uri + "/something"; // why is this allowed and compiler doesnt complain?

我本以为编译器会抱怨向 URI 类型添加字符串

2 个答案:

答案 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 ...

有一些特殊情况处理
相关问题