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

前端 未结 8 968
死守一世寂寞
死守一世寂寞 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.
    

提交回复
热议问题