BeeOnRope
BeeOnRope

Reputation: 64895

Portable way to find name of main class from Java code

Is there any way to find the name of the main class used to launch the current JVM, from arbitrary code running in that JVM?

By arbitrary, I mean that the code is not necessarily running in the main thread, or may be running in the main thread before main has even been called (e.g., code in a user-supplied java.system.classloader, which runs before main since it's used to load main) - so examining the call stack is not possible.

Upvotes: 3

Views: 1993

Answers (1)

Adisesha
Adisesha

Reputation: 5258

This is the closest I can get and you can take it from here.I can not guarantee that it is truly portable and it will not work if any method is invoking main method of another class.Let me know if you find more clean solution

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;
    }
}

Upvotes: 8

Related Questions