Reputation: 16139
Is there a quick way in java to get the nest/recurse level?
I'm writing a function to make a list of Groups and their members. The members can be groups as well. It's possible that we could end up with a circular set of groups/member.
I would like to stop at some arbitrary level.
I know I could just keep a variable in a higher scope or pass an incremented parameter but am wondering if there is any stack level information immediately available in Java.
I suppose even if there is, the trick would be to know at which level of nesting you would like to start counting at. So, the point may be moot, however I am still interested if there is any quick info on it.
Upvotes: 2
Views: 237
Reputation: 3078
java.lang.Throwable does have the method getStackTrace() which gives you an array of StackTraceElements
Upvotes: 0
Reputation: 346317
You should adress the problem of detecting cycles directly, not via an arbitrary limit of the nesting depth. Keep a Set of nodes you have already visited and check if the current one is in there.
Upvotes: 1
Reputation: 30014
No need for a Throwable
It won't be fast, but you can use this: http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace()
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
You'll have to traverse the stack in a meaninful way, but that should get you started
Upvotes: 4
Reputation: 7168
You can make a throwable at where you want it and and call getStackTrace()
Upvotes: 1