有没有办法找到在 Java 中运行的程序的名称?main 方法的类就足够了。
8 回答
试试这个:
StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName ();
当然,这仅在您从主线程运行时才有效。不幸的是,我认为您没有可以查询的系统属性来找出这一点。
编辑:引用@John Meagher 的评论,这是个好主意:
要扩展@jodonnell,您还可以使用 Thread.getAllStackTraces() 获取系统中的所有堆栈跟踪。从这里您可以搜索“主”线程的所有堆栈跟踪以确定主类是什么。即使您的类没有在主线程中运行,这也将起作用。
System.getProperty("sun.java.command")
要扩展@jodonnell,您还可以使用Thread.getAllStackTraces()获取系统中的所有堆栈跟踪。从这里您可以搜索main
Thread 的所有堆栈跟踪以确定主类是什么。即使您的类没有在主线程中运行,这也将起作用。
这是我在使用 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;
}
用于在静态上下文中访问类对象
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());
}
}
显然这里所有 3 个调用都会返回
class ClassUtils
但你明白了;
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.
试试这个 :
Java 类有自己的类的静态实例(java.lang.Class 类型)。
这意味着如果我们有一个名为 Main 的类。然后我们可以通过 Main.class 获取它的类实例
如果你只对名字感兴趣,
字符串类名 = Main.class.getName();
或者你可以只使用 getClass()。您可以执行以下操作:
public class Foo
{
public static final String PROGNAME = new Foo().getClass().getName();
}
然后 PROGNAME 将在 Foo 中的任何位置可用。如果您不在静态上下文中,则可以使用它变得更容易:
String myProgramName = this.getClass().getName();