gpt4 book ai didi

java - 如何找出JVM或现有进程调用了main方法?

转载 作者:行者123 更新时间:2023-12-02 06:03:17 24 4
gpt4 key购买 nike

考虑以下代码

public static void main(String...arg){
//do something
if(<<the method has called by a new process>>){System.exit(0);}
else{System.setProperty("main_result","0");return;}
}

main方法会被JVM或现有进程的单独进程调用,现在我怎样才能找到它?
提前致谢

最佳答案

让我们澄清一下:可能有另一个带有 main 的类已启动,或者 main 以某种方式再次被调用。

通常您想要调用 System.exit(0) (或 return;?),但是当从程序本身调用时,您希望以 System 结束.setProperty("main_result","0");.

public static void otherMain(String[] args) {  
Main.main(args);
}

public static void main(String[] args) {

...

StackTraceElement[] elems = Thread.currentThread().getStackTrace();
//for (StackTraceElement elem : elems) {
// System.out.printf("%s%n", elem.getClassName());
//}
if (elems.length > 2) { // [0] Thread [1] main
System.setProperty("main_result","0");
}
}

关于java - 如何找出JVM或现有进程调用了main方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22500657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com