Java 中的 $0(程序名称)?发现主类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:32:13  来源:igfitidea点击:

$0 (Program Name) in Java? Discover main class?

java

提问by ryantm

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.

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

采纳答案by jodonnell

Try this:

尝试这个:

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

Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out.

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

Edit:Pulling in @John Meagher's comment, which is a great idea:

编辑:引用@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.

要扩展@jodonnell,您还可以使用 Thread.getAllStackTraces() 获取系统中的所有堆栈跟踪。从这里您可以搜索“主”线程的所有堆栈跟踪以确定主类是什么。即使您的类没有在主线程中运行,这也将起作用。

回答by polarbear

Also from the command line you could run the jpstool. Sounds like a

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

jps -l 

will get you what you want.

会给你你想要的。

回答by 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 mainThread to determine what the main class is. This will work even if your class is not running in the main thread.

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

回答by Adam

Or you could just use getClass(). You can do something like:

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

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

And then PROGNAME will be available anywhere inside Foo. If you're not in a static context, it gets easier as you could use this:

然后 PROGNAME 将在 Foo 内的任何地方可用。如果您不在静态上下文中,则可以更轻松地使用它:

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

回答by color

Try this :

尝试这个 :

Java classes have static instance of their own class (java.lang.Class type).

Java 类具有它们自己的类(java.lang.Class 类型)的静态实例。

That means if we have a class named Main. Then we can get its class instance by Main.class

这意味着如果我们有一个名为 Main 的类。然后我们可以通过 Main.class 获取它的类实例

If you're interested in name only then,

如果你只对名字感兴趣,

String className = Main.class.getName();

String className = Main.class.getName();

回答by tschodt

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

显然,这里所有 3 个调用都将返回

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.

回答by Andrew Taylor

This is the code I came up with when using the combined responses of jodonnell and John Meagher. It stores the main class in a static variable to reduce overhead of repeated calls:

这是我在使用 jodonnell 和 John Meagher 的组合响应时想出的代码。它将主类存储在一个静态变量中以减少重复调用的开销:

private static Class<?> mainClass;

public static Class<?> getMainClass() {
  if (mainClass != null)
    return mainClass;

  Collection<StackTraceElement[]> stacks = Thread.getAllStackTraces().values();
  for (StackTraceElement[] currStack : stacks) {
    if (currStack.length==0)
      continue;
    StackTraceElement lastElem = currStack[currStack.length - 1];
    if (lastElem.getMethodName().equals("main")) {
      try {
        String mainClassName = lastElem.getClassName();
        mainClass = Class.forName(mainClassName);
        return mainClass;
      } catch (ClassNotFoundException e) {
        // bad class name in line containing main?! 
        // shouldn't happen
        e.printStackTrace();
      }
    }
  }
  return null;
}

回答by Nadav Brandes

System.getProperty("sun.java.command")