java 如何在java中获取主类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14036053/
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-10-31 14:50:31  来源:igfitidea点击:

How to get the main class name in java

javastack-trace

提问by Karthikeyan

How to get the main class name in any point of my java execution. all that i wanted is i need to get the class name from where my execution has started. Example,

如何在我的 java 执行的任何一点获取主类名。我想要的只是我需要从我的执行开始的地方获取类名。例子,

package mypackage;
class A
{
public static sayName()
{
 System.out.println("Here i have to print the class name B");
}
}


package test;
import mypackage.A;

class B
{
public static void main()
{
A.sayName();
}
}

Thanks in advance

提前致谢

回答by Vallabh Patade

See if this works.

看看这是否有效。

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

But I am not sure if it will work if execution of this code has another thread of control other than main thread.

但是我不确定如果此代码的执行具有除主线程之外的另一个控制线程,它是否会起作用。

回答by harikrishnan.n0077

Try this

试试这个

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

This might work but it's not portable between JVMs.

这可能有效,但它不能在 JVM 之间移植。

回答by Timofei

I'll create additional holder class which will hold main class name. Something like that:

我将创建额外的持有者类,该类将保存主类名称。类似的东西:

public class MainClassHolder{
    private static String className = null;

    public static void setClassName(String name) {
         className = name;
    }
    public static String getClassName() {
         return className;
    }
} 

Then in main methot you'll set up className into holder

然后在主方法中,您将把 className 设置为 holder

package mypackage;
class A
{
public static sayName()
{
 System.out.println(MainClassHolder.getClassName());
}
}


package test;
import mypackage.A;

class B
{
public static void main()
{
    MainClassHolder.setClassName(B.class.getName());
    A.sayName();
}
}