首页 > 解决方案 > 如何使用 Java 9+ 从 Process 获取 pid 而没有非法访问警告?

问题描述

我需要为我启动的进程获取底层操作系统 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 特定的 Process 子类不存储“pid”字段而是“handle”字段(所以你需要做一点 JNA 来获取实际的 pid),另一个是从 Java 9 开始它会触发一堆可怕的警告,比如“警告:发生了非法反射访问操作”。

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

标签: javareflectionprocesspidjava-9

解决方案


您可以使用Process#pidJava9 中引入的,示例如下:

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

推荐阅读