有没有一种方法可以在System.out中添加一个名为printlnx的方法,该方法将以字符串作为输出的前缀?

| 有没有一种方法可以在System.out中添加一个名为printlnx的方法,该方法将以字符串作为输出的前缀? 所以,如果我打电话给:
System.out.printlnx(\"This is a test\");
它会打印一个前缀(由我指定):
-prefix-->This is a test
注意:我的意图是标记控制台程序的所有输出,以便其输出看起来与随后运行的辅助控制台程序不同。     
已邀请:
        
System.out
实际上是
PrintStream
类型的对象。您不能向任意对象追溯添加任意方法。 但是您可以很容易地编写一个位于您自己的名称空间中的代码:
public final class utils {
    public static void printlnx(String str) {
        System.out.println(\"-prefix-->\" + str);
    }
}
然后在其他地方:
...

utils.printlnx(\"This is a test\");
    
        您不能将方法添加到现有的类中。至少并非没有费力的努力,在这种情况下这将是毫无意义的。您有两个选择。一种是拥有自己的实用程序方法,如其他答案所述。 另一个选择是围绕现有System.out制作包装器PrintStream,以为每行添加前缀,然后通过System.setOut()方法对其进行重新分配。您甚至可以在其中放置自己的方法,但必须强制转换:
((MyPrintStream)System.out).printlnx(...)
这是我验证过的完整示例:
public class Test {
    public static void main(String argv[]) {
        System.setOut(new MyPrintStream());
        ((MyPrintStream)System.out).printlnx(\"Hello\");
    }

    private static class MyPrintStream extends PrintStream {

        public MyPrintStream() {
            super(System.out);
        }

        public void printlnx(String str) {
           super.println(\"prefix: \" + str);
        }
    }
}
    

要回复问题请先登录注册