如何将对“ System.out.println”的引用分配给变量?

时间:2018-11-02 10:25:41

标签: java

我想将引用分配给变量p:

import curses


def main(stdscr):
    board = [
        ['E', 'B', 'C', 'D'],
        ['C', 'F', 'G', 'H'],
        ['I', 'J', 'K', 'L'],
        ['M', 'N', 'O', 'P'],
    ]

    curses.echo()  # we want to see user input on screen

    user_guess_prompt = 'your guess: '
    guess_line = len(board) + 1 + 2
    guess_column = len(user_guess_prompt)
    max_guess_size = 15

    guess = None
    while guess != 'q':
        # clear the entire screen
        stdscr.clear()

        # a bit of help on how to quit (unlike print, we have to add our own new lines)
        stdscr.addstr('enter q as a guess to exit\n\n')

        # print the board
        for line in board:
            stdscr.addstr(' '.join(line)+'\n')

        # tell the use about their previous guess
        if guess == 'mice':
            stdscr.addstr(guess + ' is correct!\n')
        elif guess is None:
            stdscr.addstr('\n')
        else:
            stdscr.addstr(guess + ' is wrong!\n')

        # prompt for the user's guess
        stdscr.addstr(user_guess_prompt)

        # tell curses to redraw the screen
        stdscr.refresh()

        # get user input with the cursor initially placed at the given line and column 
        guess = stdscr.getstr(guess_line, guess_column, max_guess_size).decode('ascii')


if __name__ == '__main__':
    curses.wrapper(main)

以便我可以像这样使用它:

Function<?, Void> p = System.out::println; // [1]

表达式[1]产生编译错误,该如何解决?

  

线程“ main”中的异常java.lang.Error:未解决的编译问题:

     

PrintStream类型的println(Object)类型为void,这与描述符的返回类型不兼容

如果将p("Hello world"); // I wish `p` to behave exactly same as `System.out.println` 更改为Void,错误将变为:

  

线程“主”中的异常java.lang.Error:未解决的编译问题:       语法错误,插入“尺寸”以完成ReferenceType

2 个答案:

答案 0 :(得分:10)

不幸的是,您无法将System.out.println的所有重载都放在一个变量中,这似乎是您试图在此处进行的操作。另外,您应该使用功能接口Consumer代替Function

您可以在System.out.println中存储最通用的Object重载,它是占用Consumer<Object>的重载:

Consumer<Object> println = System.out::println;
println.accept("Hello World!");

或者,如果您只想要接受String的重载,

Consumer<String> println = System.out::println;

请注意,使用功能接口无法实现所需的语法(直接print("Hello World"))。

还请注意,如果将char[]传递给println.accept,它的行为将与System.out.println(char[])不同。如果这困扰您,您可以改为使用静态导入:

import static java.lang.System.out;

然后您可以这样做:

out.println(...);

答案 1 :(得分:3)

PrintStream out = System.out;
out.println("helo world");

为什么不只将System.out保存到变量中然后使用它?

另一种不松散println()编译时间检查的解决方案,是使用String.format()函数。您可以将其添加到变量中:

BiConsumer<String, Object> println = (format, args) -> System.out.println(String.format(format, args));
println.accept("hello world", null);