java - How to assign a reference of `System.out.println` to a variable?
问题描述
I want to assign the reference to variable p:
Function<?, Void> p = System.out::println; // [1]
so that I can use it like:
p("Hello world"); // I wish `p` to behave exactly same as `System.out.println`
Expression [1] produce a compilation error, how to resolve it?
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The type of println(Object) from the type PrintStream is void, this is incompatible with the descriptor's return type: Void
If change Void
to void
the error becomes:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert "Dimensions" to complete ReferenceType
解决方案
不幸的是,您不能将 的所有重载System.out.println
放入一个变量中,这似乎是您在这里尝试做的。此外,您应该使用功能接口Consumer
而不是Function
.
您可以将最通用的重载存储在 a 中,System.out.println
即采用, 的重载:Object
Consumer<Object>
Consumer<Object> println = System.out::println;
println.accept("Hello World!");
或者,如果您只想要接受 a 的重载String
,
Consumer<String> println = System.out::println;
print("Hello World")
请注意,使用功能接口(直接)实现您想要的语法是不可能的。
另请注意,如果您将 a 传递char[]
给println.accept
,它的行为方式将与System.out.println(char[])
. 如果这让您感到困扰,您可以改用静态导入:
import static java.lang.System.out;
然后你可以这样做:
out.println(...);
推荐阅读
- bash - 如何将不同的值一个接一个地用作同一个参数?
- django - 在 django 电子商务网站中完成付款后重定向用户
- javascript - 如何使用 javascript/node.js 从流行语中获取 Youtube 视频 URL
- c++ - C++强制派生类实现静态函数
- plotly - data-dash-is-loading 何时触发回调函数?
- java - 如何从堆栈中获得真正的 LIFO 订单?
- go - 如何将 nil/null 参数传递给存储函数?
- oracle - 在 Oracle 中,我有季度名称和开始期和结束期,如何将所有这些季度转换为年份?
- javascript - 为什么 React 开发工具将我的组件显示为匿名?
- node.js - Docker 容器中的 Nodejs 和 React