Get the current process ID in JDK 1.5

The following example is platform-dependent and was only tested with Sun’s JVM 1.5.0 on Windows XP. It first shows you how to get it using the standard management API’s and then using some reflection tricks and the undocumented sun.* classes. (Using RuntimeMBean):


public class Main
   public static void main(String []args) {
      RuntimeMBean mbean = ManagementFactory.getRuntimeMBean();
      String name = mbean.getName();
} (Using reflection):

import java.lang.reflect.*;

public class Main
   public static void main(String []args) throws Exception {
      int pid = getProcessId();
      System.out.println("Current processID: " + pid);
      try {
      catch(Exception e) { }
   public static int getProcessId() throws Exception {
      // next line to trigger loading of library
      Class c = Class.forName("");
      //VMManagementImpl impl = new VMManagementImpl();
      Constructor constructor = c.getDeclaredConstructor(new Class[] { });
      Object impl = constructor.newInstance(new Object[] { });
      Method m = c.getDeclaredMethod("getProcessId", new Class[] { });
      Object result = m.invoke(impl, new Object[] { });
      return (Integer) result;

Note that I’ve written a DLL / so before to get the process ID using JNI in all JDK versions.
It can be found here.