![](/img/trans.png)
[英]need to figure out how to manipulate the mutator to figure out a class according to professor, I am confusd on how to do that
[英]How do I figure out which class was executed as the main class?
最终,我想要的是类似于该问题的答案:
有一个转折。 与示例不同,我不知道在编译时哪个类将包含main方法。 但是,如果我知道首先调用哪个类,则可以找到执行我的应用程序的位置。
所以我的问题是:如何发现哪个类包含执行Java应用程序所调用的主要方法?
编辑(澄清):
我想让一个图书馆知道我正在运行的应用程序的“名称”。 因此,如果我输入java -cp ... MyMainClass,而我的主类恰好位于文件夹/usr/something/myApp/lib/MyMainClass.jar中,那么我可以报告“ myApp”。 这是推断我程序名称的后备默认选项。
如果您在程序的主线程中,则可以执行以下操作:
StackTraceElement[] stackTrace = new Exception().getStackTrace();
String className = stackTrace[stackTrace.length - 1].getClassName();
正如@Makoto所说,它可能对解释为什么需要执行此操作很有用; 可能有更好的方法,具体取决于您启动应用程序的方式。
要获取入口点,而不依赖于线程,可以检索所有堆栈跟踪,并在id == 1
那一个中选择最高点,例如(Java 8):
StackTraceElement[] stackTrace = Thread.getAllStackTraces()
.entrySet()
.stream()
.filter(entry -> entry.getKey().getId() == 1)
.findFirst().get()
.getValue();
System.out.println(stackTrace[stackTrace.length - 1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.