Getting JVM main class and program args via JMX
See how to get pid in previous post
See the article about how to get main class and program args via JMX from anywhere in app, not passed from main which would require clients to make them available.
See the article about how to get main class and program args via JMX from anywhere in app, not passed from main which would require clients to make them available.
public class RuntimeInfo {
private static volatile RuntimeInfo instance;
private String host;
private String pid;
private String mainClass;
private String args;
private RuntimeInfo() {
}
public static synchronized RuntimeInfo getInstance() {
if (instance != null) {
return instance;
}
instance = new RuntimeInfo();
instance.acquireHostAndPid();
instance.acquireMainClassAndArgs();
return instance;
}
private void acquireMainClassAndArgs() {
for (VirtualMachineDescriptor vd : VirtualMachine.list()) {
final String[] virtualMachineNameTokens = vd.toString().split(" ");
if (!virtualMachineNameTokens[1].equals(pid)) {
continue;
}
final String virtualMachineName = vd.toString();
mainClass = parseMainClass(virtualMachineName);
args = parseArgs(virtualMachineName);
}
}
private String parseArgs(final String virtualMachineName) {
if (virtualMachineName.split(" ").length < 4) {
return "";
}
int ptr = 0;
for (int i = 0; i < 3; i++) {
ptr = virtualMachineName.indexOf(' ', ptr + 1);
}
return virtualMachineName.substring(ptr + 1);
}
private String parseMainClass(final String virtualMachineName) {
final String[] virtualMachineNameTokens = virtualMachineName.split(" ");
return virtualMachineNameTokens[2];
}
private void acquireHostAndPid() {
final RuntimeMXBean r = ManagementFactory.getRuntimeMXBean();
final String name = r.getName();
host = name.substring(name.indexOf('@') + 1);
pid = name.substring(0, name.indexOf('@'));
}
public static void main(final String[] args) {
final RuntimeInfo ri = getInstance();
System.out.println(ri.toString());
}
@Override
public String toString() {
return "host=" + host + ", pid=" + pid + ", mainClass=" + mainClass + ", args=[" + args + "]";
}
}
Comments