问题描述
是否可以获取程序当前正在运行的VM?我知道有一种VirtualMachine.list()
方法,但我不知道如何找到正确的方法。我无法搜索特定的displayName
,因为它是动态的。
还有找到正确虚拟机的另一种方法吗?
解决方法
要附加到的VM的ID是进程ID(pid)。因此,您只需要find pid of the current JVM process。
这是一种实现方法:
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
String jvmPid = jvmName.substring(0,jvmName.indexOf('@'));
VirtualMachine self = VirtualMachine.attach(jvmPid);
注意:由于JDK 9附加到当前进程需要设置系统属性:
-Djdk.attach.allowAttachSelf=true