springboot的源碼中有這么一段代碼
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;
}
其中以下這句代碼就能獲取到當(dāng)前應(yīng)用正在執(zhí)行的代碼流(棧楨),數(shù)據(jù)的第一個(gè)元素就是當(dāng)前正在執(zhí)行的方法
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();