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;
}
It works but there are several problems with this approach, one being that you need to do extra work on Windows because the Windows-specific Process subclass doesn't store a "pid" field but a "handle" field (so you need to do a bit of JNA to get the actual pid), and another being that starting with Java 9 it triggers a bunch of scary warnings like "WARNING: An illegal reflective access operation has occurred".问题:是否有更好的方法(清洁,独立,保证不在Java的将来发行版)获得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