@ Nullable public static StackTraceElement findCallerOf ( Class < ? > target , Throwable throwable , int skip ) { checkNotNull ( target , "target" ) ; checkNotNull ( throwable , "throwable" ) ; if ( skip < 0 ) { throw new IllegalArgumentException ( "skip count cannot be negative: " + skip ) ; } // Getting the full stack trace is expensive, so avoid it where possible. StackTraceElement [ ] stack = ( stackGetter != null ) ? null : throwable . getStackTrace ( ) ; // Note: To avoid having to reflect the getStackTraceDepth() method as well, we assume that we // will find the caller on the stack and simply catch an exception if we fail (which should // hardly ever happen). boolean foundCaller = false ; try { for ( int index = skip ; ; index ++ ) { StackTraceElement element = ( stackGetter != null ) ? stackGetter . getStackTraceElement ( throwable , index ) : stack [ index ] ; if ( target . getName ( ) . equals ( element . getClassName ( ) ) ) { foundCaller = true ; } else if ( foundCaller ) { return element ; } } } catch ( Exception e ) { // This should only happen is the caller was not found on the stack (getting exceptions from // the stack trace method should never happen) and it should only be an // IndexOutOfBoundsException, however we don't want _anything_ to be thrown from here. // TODO(dbeaumont): Change to only catch IndexOutOfBoundsException and test _everything_. return null ; } }
Returns the stack trace element of the immediate caller of the specified class .