以下是我正在使用的方法,在您无法控制主机的情况下:
public static Class> getMainClass() {
// find the class that called us, and use their "target/classes"
final Map traces = Thread.getAllStackTraces();
for (Entry trace : traces.entrySet()) {
if ("main".equals(trace.getKey().getName())) {
// Using a thread named main is best...
final StackTraceElement[] els = trace.getValue();
int i = els.length - 1;
StackTraceElement best = els[--i];
String cls = best.getClassName();
while (i > 0 && isSystemClass(cls)) {
// if the main class is likely an ide,
// then we should look higher...
while (i-- > 0) {
if ("main".equals(els[i].getMethodName())) {
best = els[i];
cls = best.getClassName();
break;
}
}
}
if (isSystemClass(cls)) {
i = els.length - 1;
best = els[i];
while (isSystemClass(cls) && i --> 0) {
best = els[i];
cls = best.getClassName();
}
}
try {
Class mainClass = Class.forName(best.getClassName());
return mainClass;
} catch (ClassNotFoundException e) {
throw X_Util.rethrow(e);
}
}
}
return null;
}
private static boolean isSystemClass(String cls) {
return cls.startsWith("java.") ||
cls.startsWith("sun.") ||
cls.startsWith("org.apache.maven.") ||
cls.contains(".intellij.") ||
cls.startsWith("org.junit") ||
cls.startsWith("junit.") ||
cls.contains(".eclipse") ||
cls.contains("netbeans");
}