$ 0(程序名称)在Java中?发现主班?

时间:2020-03-05 18:47:05  来源:igfitidea点击:

有没有办法找到在Java中运行的程序的名称? main方法的类就足够了。

解决方案

回答

试试这个:

StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
    StackTraceElement main = stack[stack.length - 1];
    String mainClass = main.getClassName ();

当然,这仅在从主线程运行时才有效。不幸的是,我认为没有系统属性可以查询找到。

编辑:拉入@John Meagher的评论,这是一个好主意:

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.

回答

我们也可以从命令行运行jps工具。听起来像

jps -l

会得到你想要的东西。

回答

要在@jodonnell上进行扩展,我们还可以使用Thread.getAllStackTraces()获取系统中的所有堆栈跟踪。由此,我们可以在所有堆栈跟踪中搜索main线程,以确定主类是什么。即使类不在主线程中运行,这也将起作用。

回答

或者我们可以只使用getClass()。我们可以执行以下操作:

public class Foo
{
    public static final String PROGNAME = new Foo().getClass().getName();
}

然后,PROGNAME将在Foo内部的任何位置可用。如果我们不在静态环境中,则可以使用以下命令变得更加容易:

String myProgramName = this.getClass().getName();