如何使用 Java 9+ 从进程中获取 pid 而没有非法访问警告?

How to obtain pid from Process without illegal access warning with Java 9+?

我需要为我启动的进程获取基础 OS PID。我现在使用的解决方案涉及使用如下代码通过反射访问私有字段:

private long getLongField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException {
    Field field = target.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    long value = field.getLong(target);
    field.setAccessible(false);
    return value;
}

它有效,但这种方法有几个问题,一个是你需要在 Windows 上做额外的工作,因为 Windows-specific Process 子类不存储 "pid" 字段但是一个 "handle" 字段(所以你需要做一些 JNA 来获取实际的 pid),另一个是以 Java 9 开头的字段会触发一堆可怕的警告,比如 "WARNING: An illegal reflective access operation has occurred".

所以问题是:是否有更好的方法(干净,OS 独立,保证在 Java 的未来版本中不会中断)获取 pid?这不应该由 Java 首先公开吗?

您可以使用 Java9 中介绍的 Process#pid,其示例如下:

ProcessBuilder pb = new ProcessBuilder("echo", "Hello World!");
Process p = pb.start();
System.out.printf("Process ID: %s%n", p.pid());

该方法的文档如下:

* Returns the native process ID of the process.
* The native process ID is an identification number that the operating
* system assigns to the process.

同样值得关注

* @throws UnsupportedOperationException if the Process implementation
*         does not support this operation