Hiding System.out.print calls of a class

前端 未结 5 1407
别那么骄傲
别那么骄傲 2021-02-02 13:16

I\'m using a java library (jar file). The author of the file put in a bunch of System.out.print and System.out.printlns. Is there any way to hide these

5条回答
  •  孤独总比滥情好
    2021-02-02 13:46

    If you have a bigger programm consider something like

    public abstract class Output {
        private static final PrintStream out = System.out;
        private static final PrintStream dummy = new PrintStream(new OutputStream() {@Override public void write(int b){} });
    
        private static boolean globalOutputOn = true;
        public static void toggleOutput() {
            System.setOut((globalOutputOn=!globalOutputOn)?dummy:out);
        }
    
        public static void toggleOutput(boolean on) {
            globalOutputOn = on;
            System.setOut(on?out:dummy);
        }
    }
    

    This gurantees that you can toggle output on and off in different classes, while beeing guranteed to be able to turn the output on later.

    You for example use it by calling

    toggleOutput(false) at the start of each method and

    toggleOutput(true) at the end of each method.

提交回复
热议问题