/** * Gets the caller stack trace of the method or constructor which calls it. * * @param excludedMethods * the excluded methods * @param excludedClasses * the excluded classes * @return the caller stack trace * @since 1.4.2 (17.05.2014) */ public static StackTraceElement[] getCallerStackTrace(final Pattern[] excludedMethods, final Class<?>... excludedClasses) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); int i = 2; String scannerClassName = StackTraceScanner.class.getName(); for (; i < stackTrace.length - 1; i++) { if (!scannerClassName.equals(stackTrace[i].getClassName())) { break; } } for (; i < stackTrace.length - 1; i++) { if (!matches(stackTrace[i].getMethodName(), excludedMethods) && !matches(stackTrace[i].getClassName(), excludedClasses)) { break; } } return ArrayUtils.subarray(stackTrace, i, stackTrace.length); }
/** * Gets the caller of the given method. * * @param classname * the classname * @param methodName * the method name * @param excluded * a list of filters which should be not considered as caller * @return the caller of */ public static StackTraceElement getCallerOf(final String classname, final String methodName, final Pattern... excluded) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (int i = getIndexOf(classname, methodName, stackTrace) + 1; i < stackTrace.length; i++) { if (!matches(stackTrace[i].getMethodName(), excluded)) { return stackTrace[i]; } } throw new NotFoundException(classname + "." + methodName + "()"); }
/** * Gets the caller of a constructor. * * @param clazz * the clazz * @param excluded * the excluded * @return the caller of constructor */ public static StackTraceElement getCallerOfConstructor(final Class<?> clazz, final Pattern... excluded) { try { return getCallerOf(clazz, "<init>", excluded); } catch (NotFoundException nfe) { LOG.trace("Caller of constructor of {} not found:", clazz, nfe); LOG.debug("Looking for adviced init method because of {}", nfe.getMessage()); StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (int i = 1; i < stackTrace.length; i++) { if (stackTrace[i].getMethodName().startsWith("init$")) { for (int j = i + 1; j < stackTrace.length; j++) { if (!matches(stackTrace[j].getMethodName(), excluded)) { return stackTrace[j]; } } break; } } throw new NotFoundException( "new " + clazz.getSimpleName() + "(..) not part of " + Converter.toShortString(stackTrace)); } }