Stack { public static StackTraceElement caller() { Exception e = new Exception(); List<StackTraceElement> frames = Arrays.asList( e.getStackTrace() ); frames = removeFramesWithDuplicateClasses( frames ); int idx = -1; for (int i = 0; i < frames.size(); i++) { StackTraceElement frame = frames.get( i ); if ( frame.getClassName().equals( Stack.class.getName() ) ) { idx = i + 2; } } if ( idx == -1 ) throw new RuntimeException( "Unable to determine caller" ); for (int i = idx; i < frames.size(); i++) { StackTraceElement frame = frames.get( i ); String frameClassName = frame.getClassName(); if ( frameClassName.startsWith( "sun.reflect." ) || frameClassName.startsWith( "java.lang.reflect." ) ) { continue; } if ( frameClassName.startsWith( "com.google.inject.internal." ) ) { continue; } return frame; } throw new RuntimeException( "Unable to determine caller" ); }  static StackTraceElement caller();  }
@Test public void testCaller() throws Exception { assertEquals( "org.junit.runners.model.FrameworkMethod$1", Stack.caller().getClassName() ); assertEquals( "org.junit.runners.model.FrameworkMethod$1", fromWithinSameClass().getClassName() ); }