$0 (Program Name) in Java? Discover main class?

前端 未结 8 947
死守一世寂寞
死守一世寂寞 2020-12-03 00:23

Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.

相关标签:
8条回答
  • 2020-12-03 01:09

    For access to the class objects when you are in a static context

    public final class ClassUtils {
        public static final Class[] getClassContext() {
            return new SecurityManager() { 
                protected Class[] getClassContext(){return super.getClassContext();}
            }.getClassContext(); 
        };
        private ClassUtils() {};
        public static final Class getMyClass() { return getClassContext()[2];}
        public static final Class getCallingClass() { return getClassContext()[3];}
        public static final Class getMainClass() { 
            Class[] c = getClassContext();
            return c[c.length-1];
        }
        public static final void main(final String[] arg) {
            System.out.println(getMyClass());
            System.out.println(getCallingClass());
            System.out.println(getMainClass());
        }
    }
    

    Obviously here all 3 calls will return

    class ClassUtils
    

    but you get the picture;

    classcontext[0] is the securitymanager
    classcontext[1] is the anonymous securitymanager
    classcontext[2] is the class with this funky getclasscontext method
    classcontext[3] is the calling class
    classcontext[last entry] is the root class of this thread.
    
    0 讨论(0)
  • 2020-12-03 01:17

    To expand on @jodonnell you can also get all stack traces in the system using Thread.getAllStackTraces(). From this you can search all the stack traces for the main Thread to determine what the main class is. This will work even if your class is not running in the main thread.

    0 讨论(0)
提交回复
热议问题