samedi 3 juillet 2021

How would I get the name of the class that has an inherited main method?

I have an Application class that is the base class for a ClientApplication. The Application has a main method that prints the name of the class that was defined to invoke the main method.

public abstract class Application {
  // Using this class as the entry point would output "Application"
  public static void main ( String... args ) {
    // Print the name of the class that is calling the main method
  }
}

public class ClientApplication extends Application {
  // Using this class as the entry point would output "ClientApplication"
  // main is inherited and can be invoked via the ClientApplication class.
}

I have tried to use an instantiated Object to get the name of the class like so:

public abstract class Application {
  public static void main( String... args ) {
    System.out.println( new Object() {}.getClass().getEnclosingClass().getSimpleName() );
  }
}

But that prints out "Application" no matter which class is defined as the class that contains the main method.





Aucun commentaire:

Enregistrer un commentaire