Java中的$ 0(程序名)?发现主要课程? [英] $0 (Program Name) in Java? Discover main class?

查看:115
本文介绍了Java中的$ 0(程序名)?发现主要课程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

试试这个:

    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.

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

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


要扩展@jodonnell,您还可以
获取系统中的所有堆栈跟踪
使用Thread.getAllStackTraces()。从
这个你可以搜索主线程的所有堆栈
跟踪到
确定主类是什么。即使你的班级不是在主线程中运行的
,这个
也会有效。

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.

这篇关于Java中的$ 0(程序名)?发现主要课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆