简体   繁体   English

如何在Java方法中使用System.out作为参数

[英]How to use System.out as an argument in method in java

I have a method in java display, 我在Java显示中有一个方法,

when i used C++, it seems that I could display(ListNode L, OutputStream out) but, could I then out System.out in it? 当我使用C ++时,似乎可以display(ListNode L, OutputStream out)但是我可以在其中display(ListNode L, OutputStream out) System.out吗? it seems out.write is ok not out.println? 似乎out.write可以不可以out.println吗?

What should I do if I want to use System.out as parameter? 如果我想使用System.out作为参数怎么办?

Since the member System.out is of class PrintStream you could do: 由于成员System.outPrintStream类的,因此您可以执行以下操作:

void display(PrintStream out) {
    out.println("42!");
}

For better visualization of the hierarchy: 为了更好地显示层次结构:

Object
  |---OutputStream
  |     |---FileOutputStream
  |     |---FilterOutputStream
  |           |---PrintStream (System.out)
  |
  |---InputStream (System.in)
  |     |---FileInputStream

To solve the real problem, think about having an interface with two classes which implements it. 为了解决实际的问题,请考虑使用一个具有两个实现它的类的接口。

For example (without exception handling): 例如(没有异常处理):

interface Display {
    void display(String message);
}

class ConsoleDisplay implements Display {
    void display(String message) {
        System.out.println(message);
    }
}

class FileDisplay implements Display {
    FileOutputStream out;

    FileDisplay(String filename) {
        out = new FileOutputStream(filename);
    }

    void display(String message) {
        out.write(message.getBytes());
    }
}

class DoingStuff {
    public static void main(String[] args) {
        Display dispFile = new FileDisplay("logfile.log");
        display("42!", dispFile);

        Display dispConsole = new ConsoleDisplay();
        display("42!", dispConsole);
    }

    static void display(String message, Display disp) {
        disp.display(message);
    }
}

Why would you want to pass System.out as a parameter, when it is available everywhere? System.out随处可见时,为什么要传递System.out作为参数?

Why not just do this: 为什么不这样做:

public void display(final String toDisplay) {
    System.out.println(toDisplay);
}

Type of System.out is PrintStream. System.out的类型是PrintStream。 Here is the javadoc. 是javadoc。

In Java 8 one might think of method references as well. 在Java 8中,人们可能还会想到方法引用。

Example: 例:

private List<ListNode> nodes = new LinkedList<>();

...

nodes.forEarch(System.out :: println);

System.out is a PrintStream instance. System.out是一个PrintStream实例。 System.out.println is a method invocation on that instance. System.out.println是对该实例的方法调用。 So, you could do the following: 因此,您可以执行以下操作:

public display (ListNode l, PrintStream out) {
    out.println("L is " + l);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM