Hook into System.out.println(); and modify

前端 未结 3 1126
借酒劲吻你
借酒劲吻你 2021-01-05 17:47

I would like to modify the output printed by System.out.println();. How is this possible? It is possible - I\'ve seen it in Bukkit/Craftbukkit. If a plugin is p

3条回答
  •  春和景丽
    2021-01-05 18:04

    This question is already answered, however, I would like to add a very good method to trace prints.

    PrintStream myStream = new PrintStream(System.out) {
            @Override
            public void println(String line) {
                StackTraceElement element = new Exception().getStackTrace()[1];
                super.println("("+element.getFileName()+":"+element.getLineNumber()+") "+line);
            }
        };
    
    System.setOut(myStream);
    

    Now when you print something, it will show up like "(File:linenumber) text", and in many editors you can just click on that to jump to the location. Its probably quite expensive to get the stacktrace all the time, so probably best to only use it during debug.

提交回复
热议问题