이것은 내가 얻을 수있는 가장 가까운 것이고 여기에서 가져올 수 있습니다. 이식성이 정말 보장 할 수는 없으며 어떤 메소드가 다른 클래스의 main 메소드를 호출하는 경우 작동하지 않을 수 있습니다. 더 깨끗한 솔루션
import java.util.Map.Entry;
public class TestMain {
/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(findMainClass());
}
public static String findMainClass() throws ClassNotFoundException{
for (Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) {
Thread thread = entry.getKey();
if (thread.getThreadGroup() != null && thread.getThreadGroup().getName().equals("main")) {
for (StackTraceElement stackTraceElement : entry.getValue()) {
if (stackTraceElement.getMethodName().equals("main")) {
try {
Class<?> c = Class.forName(stackTraceElement.getClassName());
Class[] argTypes = new Class[] { String[].class };
//This will throw NoSuchMethodException in case of fake main methods
c.getDeclaredMethod("main", argTypes);
return stackTraceElement.getClassName();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
출처
2011-11-26 01:59:18
Adi
주 클래스의 주 메서드가 먼저 호출됩니다. (http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.1을 참조하십시오.) 그래서 메인이 호출되기 전에 "메인 스레드에서 실행 중일 수 있습니다" . 나는이 문장이 "정적 이니셜 라이저"또는 "Thread # run()"을 언급한다고 생각한다. – cocoatomo
@cocoatomo : 나는 뭔가를 놓치고 있습니다. 그 링크가 원래의 포스터의 질문에 대한 해결책을 제시합니까? 나는 그것을 검토했지만, 어떻게 든 그것을 놓쳤다. –
@ Hovercraft Eels의 가득 차있는 : 미안, 나는 나의 코멘트를 완료하기 전에 돌아 오는 열쇠를 밀기를 잘못했다. BeeOnRope의 의도를 이해하고 싶습니다. 그래서 BeeOnRope가 만나기를 희망합니다. – cocoatomo