Skip to content

Instantly share code, notes, and snippets.

@preslavrachev
Created July 23, 2015 07:44
Show Gist options
  • Save preslavrachev/ba5e0f93e415604d82fa to your computer and use it in GitHub Desktop.
Save preslavrachev/ba5e0f93e415604d82fa to your computer and use it in GitHub Desktop.
Spring Boot has a funky (and interesting) way of finding out the main application class. Basically, the method throws a runtime exception, which it swallows. The exception provides a list of stack trace elements, which the method loops through to find the one point on the stack, whose method name equals to "main".
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment