gpt4 book ai didi

java - 是否可以获得用于在 java 中启动 jvm 的命令?

转载 作者:IT老高 更新时间:2023-10-28 20:53:23 25 4
gpt4 key购买 nike

我想知道是否可以从代码中获取用于启动 java 程序的命令。

例如如果我启动一个 java 程序:

 java -cp lib1:lib2:... -jar mylib.jar com.foo.Bar

我想得到确切的字符串(包括 jvm 参数)。

有可能吗?


评论赏金和问题

感谢大家的回复。不幸的是,我没有得到我最初想要的答案。我希望有一些可移植的解决方案可以从程序本身(包括类路径等)中获取完整的 java 命令。似乎没有可移植的解决方案,因为我使用的是 Linux,所以我使用 agodinhostLuigi R. Viggiano 的响应来解决我的问题。但是,我将赏金奖励给 rahulroc 以获得最完整(便携)的响应。对于其余的,所有人都赞成:)

最佳答案

下面提到的代码应该显示所有 JVM 参数、传递给 main 方法的参数以及主类名称。

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

import java.util.List;

public static void main(String[] args) {
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
List<String> jvmArgs = bean.getInputArguments();

for (int i = 0; i < jvmArgs.size(); i++) {
System.out.println( jvmArgs.get( i ) );
}
System.out.println(" -classpath " + System.getProperty("java.class.path"));
// print the non-JVM command line arguments
// print name of the main class with its arguments, like org.ClassName param1 param2
System.out.println(" " + System.getProperty("sun.java.command"));
}

getInputArguments 的 javadoc|

Returns the input arguments passed to the Java virtual machine which does not include the arguments to the main method. This method returns an empty list if there is no input argument to the Java virtual machine.

Some Java virtual machine implementations may take input arguments from multiple different sources: for examples, arguments passed from the application that launches the Java virtual machine such as the 'java' command, environment variables, configuration files, etc.

Typically, not all command-line options to the 'java' command are passed to the Java virtual machine. Thus, the returned input arguments may not include all command-line options.

你也可以看看:jps

It's a Java program that is able to get the full command line for all Java processes, including full class name of main class and JVM options.

你可以找到各种JVM tools的很好的总结, 包含 Java Application Launcher链接:

关于java - 是否可以获得用于在 java 中启动 jvm 的命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13958318/

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