java—如何获取具有继承的main方法的类的名称?

nc1teljy  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(439)

我有一个application类,它是clientapplication的基类。应用程序有一个main方法,它打印为调用main方法而定义的类的名称。

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

我尝试使用示例化对象来获取类的名称,如下所示:

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

但无论哪个类被定义为包含main方法的类,它都会打印出“application”。

cbeh67ev

cbeh67ev1#

使用此选项,您将获得调用方类名

public class Application {

public static void main(String[] args) throws ClassNotFoundException {
    // TODO Auto-generated method stub
    System.out.println(getCallerClass(2));
}

public static String getCallerClass(int level) throws ClassNotFoundException {
    StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
    String rawFQN = stElements[level + 1].toString().split("\\(")[0];
    String className = Class.forName(rawFQN.substring(0, rawFQN.lastIndexOf('.'))).getName();
    className = className.substring(className.lastIndexOf('.') + 1, className.length());
    return className;
}

}

相关问题