首页 > 解决方案 > 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

标签: java

解决方案


不幸的是,您不能将 的所有重载System.out.println放入一个变量中,这似乎是您在这里尝试做的。此外,您应该使用功能接口Consumer而不是Function.

您可以将最通用的重载存储在 a 中,System.out.println即采用, 的重载:ObjectConsumer<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(...);

推荐阅读