tokuhirom's Blog

jps を自前で実装してみる

tools.jar の中に入ってるクラスを呼べば、同じようなことができるとのこと。

import java.net.URISyntaxException;
import java.util.Set;

import sun.jvmstat.monitor.HostIdentifier;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;

public class MyJps {
	public static void main(String[] args) throws URISyntaxException, MonitorException {
		String hostname = null;
		final MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(new HostIdentifier(hostname));
		final Set<Integer> lvmids = monitoredHost.activeVms();
		for (Integer lvmid: lvmids) {
			String vmidString = "//" + lvmid + "?mode=r";
			final VmIdentifier vmIdentifier = new VmIdentifier(vmidString);
			final MonitoredVm vm = monitoredHost.getMonitoredVm(vmIdentifier);
			final String mainClass = MonitoredVmUtil.mainClass(vm, true);
			System.out.printf("%d %s\n", lvmid, mainClass);
		}
	}
}