tags:

views:

63

answers:

4

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.

+1  A: 

You can make a throwable at where you want it and and call getStackTrace()

yx
+3  A: 

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

basszero
+1 I knew there was another way, forgot what it was, thanks for pointing it out
yx
Thread.getStackTrace() creates a Throwable anyway. It might be clearer, but it's no more efficient.
Michael Myers
ah, here was the original thread where I saw this http://stackoverflow.com/questions/965964/how-can-i-detect-if-a-java-class-is-called-by-its-own-main-or-from-another-clas
yx
Ahh, perfect, I looked at that but glanced over the fact that it's an array. Thanks.
Tom Hubbard
@mmyers I hadn't looked at the actual source, now I know ;) thanks!
basszero
A: 

java.lang.Throwable does have the method getStackTrace() which gives you an array of StackTraceElements

slipset
+1  A: 

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.

Michael Borgwardt