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.
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.
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.