I need to write a parent Java class that classes using recursion can extend. The parent class will be be able to realize whenever the call stack changes ( you enter a method, temporarily leave it to go to another method call, or you are are finsihed with the method ) and then print it out. I want it to print on the console, but clear the console as well every time so it shows the stack horizantaly so you can see the height of each stack to see what popped off and what popped on… Also print out if a baseline was reached for recursive functions.
First. How can I using the StackTraceElements and Thread classes to detect automatically whenever the stack has popped or pushed an element on without calling it manually?
Second, how would I do the clearing thing?
For instance , if I had the code:
public class recursion(int i)
{
private static void recursion(int i)
{
if(i < 10)
System.out.println('A');
else
{
recursion(i / 10 );
System.out.println('B');
}
}
public static void main(String[] argv)
{
recursion(102);
}
}
It would need to print out the stack when entering main(), when entering recursion(102) from main(), when it enters recursion(102 / 10), which is recursion(10), from recursion(102), when it enters recursion(10 / 10), which is recursion(1) from recursion(10). Print out a message out when it reaches the baseline recursion(1).. then print out the stacks of reversed revisitation of function recursion(10), recursion(102) and main(). finally print out we are exiting main().
Threadclass allows managing OS threads, it does not have anything to do with the call-stack.StackTraceElementrepresents a stack-frame but you need aStackTraceto get to it.You are looking for a notification for when the stack-trace changes, for example a frame is added (a method is entered) or removed (a method is exited).
By far the most appropriate tool for this task is
AspectJ. It lets you defineadvices(a kind of method) that gets called (besides other cases) when other methods are entered or existed. These triggers that result in the advices getting called are calledpointcuts— they can be method entry, exit and the methods can be described using wildcards: the pointcutMyClass.get*applies to all get methods of MyClass.