简体   繁体   English

Java,使用Runtime.exec()继承类路径

[英]Java, inherit classpath with Runtime.exec()

I have a program that will create a child process, and I want it inherit all the classpath from its parent. 我有一个可以创建子进程的程序,并且我希望它从其父级继承所有类路径。 In javadoc, it says: 在javadoc中,它说:

public Process exec(String[] cmdarray, String[] envp) throws IOException 公共进程exec(String [] cmdarray,String [] envp)抛出IOException

Executes the specified command and arguments in a separate process with the specified environment. 在具有指定环境的单独进程中执行指定的命令和参数。

Given an array of strings cmdarray, representing the tokens of a command line, and an array of strings envp, representing "environment" variable settings, this method creates a new process in which to execute the specified command. 给定一个表示命令行标记的字符串数组cmdarray和一个表示“ environment”变量设置的字符串envp数组,此方法将创建一个新进程来执行指定的命令。

If envp is null, the subprocess inherits the environment settings of the current process. 如果envp为null,则子进程继承当前进程的环境设置。

When I set envp to null, it didn't inherit anything. 当我将envp设置为null时,它没有继承任何东西。

Here is the code: 这是代码:

System.out.print("Debug system path: "+System.getProperty("java.class.path"));
            startTime();
Process proc = Runtime.getRuntime().exec(cmd,null);

I can see the path information, but these path information is not inherited by the new created process. 我可以看到路径信息,但是新创建的过程不会继承这些路径信息。

How did you specify the classpath of your application? 您如何指定应用程序的类路径? If it was not through the CLASSPATH environment variable, it will not be inherited. 如果不是通过CLASSPATH环境变量,则不会被继承。

Runtime.exec method can invoke any native application, and the envp here refers to system environment, not your java environment. Runtime.exec方法可以调用任何本机应用程序,此处的envp是指系统环境,而不是Java环境。

If you want to pass your classpath to the child java process, you can do so explicitly: 如果要将类路径传递给子java进程,则可以明确地这样做:

String[] cmdarray = new String[] {
  "java", "-classpath", System.getProperty("java.class.path"), "com.example.MyChildApp", "appParam"};

Process p = Runtime.getRuntime().exec(cmdarray);

No can do. 没办法 Your 'classpath' at the time you call exec is whatever is hiding away in your current class loader at the time you call it. 调用exec时的“ classpath”就是调用它时隐藏在当前类加载器中的任何东西。 You can't, in general, ask a class loader to tell you the class path. 通常,您不能要求类加载器告诉您类路径。 It could be fetching classes from a database, or the planet Mars. 可能是从数据库或火星上获取类。

Reading java.class.path will tell you what was going on when your application started, but not what's going on at the time you go to launch something else. 阅读java.class.path会告诉您应用程序启动时正在发生什么,但不会告诉您启动其他事件时正在发生的情况。

Finally I have to insert "-cp System.getProperty("java.class.path")" into the cmd to make it work. 最后,我必须在cmd中插入“ -cp System.getProperty(“ java.class.path”)”才能使其正常工作。

Is there any better way to do that? 有什么更好的方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM