Erik R. Erik R. - 7 months ago 40
Java Question

How to determine main class at runtime in threaded java application?

I want to determine the class name where my application started, the one with the main() method, at runtime, but I'm in another thread and my stacktrace doesn't go all the way back to the original class.

I've searched System properties and everything that ClassLoader has to offer and come up with nothing. Is this information just not available?

Thanks.

Answer

I figured it out. Can anyone tell me if this environment variable will always be around in other java implementations across operating systems? This on Oracle JVM yields a String like "org.x.y.ClassName"

public static String getMainClassName()
{
  for(final Map.Entry<String, String> entry : System.getenv().entrySet())
  {
    if(entry.getKey().startsWith("JAVA_MAIN_CLASS")) // like JAVA_MAIN_CLASS_13328
      return entry.getValue();
  }
  throw new IllegalStateException("Cannot determine main class.")
}