class MyUtils{ static boolean callerIsOfClass(Class targetClass) { StackTraceElement stack[] = Thread.currentThread().getStackTrace(); // find our frame int our_frame = 0; while (!stack[our_frame].getMethodName().equals("callerIsOfClass")) { our_frame++; } // the frame that the caller cares about is 2 above StackTraceElement targetFrame = stack[our_frame + 2]; return targetFrame.getClassName().equals(targetClass.getName()); }}...void exampleFunction(){ assert MyUtils.callerIsOfClass(TheClassThatILike.class); ...}}
Hey are you bummed by the fact that Java has no "friend" keyword? How would you like it if your function could assert that it was only being called by a certain class?
Previous Entry
off and running
Next Entry
cascade-correlation
Comments
August 30, 2005 02:51 AM
Quote:Why do you do a loop to find where in the stack you are? aren't you always supposed to be on the top because you are the last caller?
Well I did a test run where it printed out what the stack actually looked like, and the first two stack frames were actually inside the Thread class. Which I guess kinda makes sense. And I didn't want to make any assumptions about how many frames Thread.getStackTrace() uses (maybe it won't use two in a later version), which is why I have that loop.
Quote:Why don't you make a method which returns a class instead of passing a class parameter and returning a boolean?
Yeah, no reason why it can't do that. My goal for this function was to make things as clean and simple as possible for the calling function.
Note that StackFrameElement can only give you the class name, so you have to use Class.forName() to get the actual class object.
Quote:
And finally i think that your method will fail (badly) if the main method calls your method!
Yeah, you're right it does fail, but all that happens is you get an ArrayIndexOutOfBoundsException.
August 30, 2005 10:13 AM
Advertisement
Latest Entries
middle of freaking nowhere
1008 views
check
1134 views
I have a logo!
1118 views
wooo
1069 views
scripting
1178 views
tool overload
1272 views
My tv has gone crazy
827 views
java svg code
1151 views
svg in java
1146 views
java scripting engine
969 views
Advertisement
Why do you do a loop to find where in the stack you are? aren't you always supposed to be on the top because you are the last caller?
Why don't you make a method which returns a class instead of passing a class parameter and returning a boolean?
And finally i think that your method will fail (badly) if the main method calls your method!