Java 显示堆栈深度的智能println
我在代码中使用System.out.println来跟踪程序的执行并获得一些有用的输出。这将在控制台中创建如下结果:Java 显示堆栈深度的智能println,java,debugging,Java,Debugging,我在代码中使用System.out.println来跟踪程序的执行并获得一些有用的输出。这将在控制台中创建如下结果: Main function. Program starts. Method getArea. Getting values Method getSide. Side is 6 Method getArea. First value is 6 Method getSide. Side is 8 Method getArea. Second value is 8 Method get
Main function. Program starts.
Method getArea. Getting values
Method getSide. Side is 6
Method getArea. First value is 6
Method getSide. Side is 8
Method getArea. Second value is 8
Method getArea. Area is 48
Main function. The final area is 48
我想创建tha方法,每次代码深入方法调用堆栈时,它都会在输出前添加一个空格。例如,相同的代码,但不是使用System.out.println,而是使用Misc.smartPrintln:
Main function. Program starts.
Method getArea. Getting values
Method getSide. Side is 6
Method getArea. First value is 6
Method getSide. Side is 8
Method getArea. Second value is 8
Method getArea. Area is 48
Main function. The final area is 48
该方法将具有以下定义:
public static void smartPrintln(String string);
我不知道如何实现这个功能。有什么办法解决这个问题吗?而且,使用记录器是否可以提供此功能?创建一个临时的可丢弃对象。 使用其getStackTrace方法分析堆栈并确定级别。 e、 g
创建一个临时的可丢弃对象。 使用其getStackTrace方法分析堆栈并确定级别。 e、 g
有趣的问题。@ob1建议的更简洁的实现:
public static void smartPrintln(String string) {
int i = new Throwable().getStackTrace().length - 1;
System.out.printf("%"+i+"s%s%n", "", string);
}
另一种解决方案是将功能直接添加到System.out.println调用中,如下所示:
System.setOut(new PrintStream(System.out) {
public void println(String x) {
printf("%"+(new Throwable().getStackTrace().length - 1)+"s", "");
super.println(x);
}
});
在此之后,对System.out.printlnString的所有调用都将由我们的过滤PrintStream实现处理。有趣的问题。@ob1建议的更简洁的实现:
public static void smartPrintln(String string) {
int i = new Throwable().getStackTrace().length - 1;
System.out.printf("%"+i+"s%s%n", "", string);
}
另一种解决方案是将功能直接添加到System.out.println调用中,如下所示:
System.setOut(new PrintStream(System.out) {
public void println(String x) {
printf("%"+(new Throwable().getStackTrace().length - 1)+"s", "");
super.println(x);
}
});
此后,,所有对System.out.printlnString的调用都将由我们的过滤PrintStream实现处理。使用Logger API或任何其他第三方API。使用Logger API或任何其他第三方API。Big+1到ob1-我从来没有想到过这种非常丑陋但非常有用的黑客攻击。Big+1到ob1-我从来没有想到过这种非常丑陋但非常有用的攻击哈克,很好。作为一种选择,考虑thule.CurrnTrave.GETStActTracle,而不是新的Spababel.GETStActTrace-避免丑陋的丢弃抛出。很好。作为一种选择,考虑thule.CurrnTrave.GETStActTracle,而不是新的Spababel.GETStActTrace-避免丑陋的抛出式投掷。