Java - 将 null 作为参数传递给 print()

标签 java reference outputstream

我想知道为什么下面的代码不起作用:

System.out.print(null);    
response.getWriter().print(null);

但是下面的方法有效:

String s = null;
System.out.print(s);
response.getWriter().print(s);

传递 null 与传递 null 引用相比有什么区别?

已编辑:前面提到的不起作用表示编译错误。

最佳答案

这是因为您可以传递对象字符串。由于 null 可以同时容纳这两种方法,因此编译器不知道使用哪种方法,从而导致编译错误。

方法定义:

相反,如果您提供 ObjectString 变量(即使它具有 null 值),编译器就会知道哪个方法使用。

编辑:这有更好的解释 in this answer 。至于指向Java规范的内部链接,可以阅读here ,这种情况适合这里:

The informal intuition is that one method is more specific than another **if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

It is possible that no method is the most specific, because there are two or more methods that are maximally specific.

关于Java - 将 null 作为参数传递给 print(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784697/

相关文章:

c++ - 局部堆栈变量成员的返回值优化

java - 是否可以使用 Java 捕获正在播放的音频?

java - 显示不同数组类型的值

java - SQLite 'INSERT OR REPLACE INTO' 不正确的行为

java - 接收数据报包不显示

c# - 使用同一 DLL 的多个版本

c++ - 为什么我不能在 C++ 中将引用存储在 `std::map` 中?

java - 随机访问文件写入以额外空格结束 Java

java - 忽略 SORT METHOD 中的符号

java - 使用 Guava 的最佳方式