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.

Main.java (Using RuntimeMBean):

import java.lang.management.*;

public class Main
{
   public static void main(String []args) {
      RuntimeMBean mbean = ManagementFactory.getRuntimeMBean();
      String name = mbean.getName();
       
      System.out.println(name);
   }
}

Main.java (Using reflection):

import sun.management.*;
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 {
         Thread.sleep(10000);
      }
      catch(Exception e) { }
   }
    
   public static int getProcessId() throws Exception {
      // next line to trigger loading of library
      ManagementFactory.getThreadMXBean();
       
      Class c = Class.forName("sun.management.VMManagementImpl");
      //VMManagementImpl impl = new VMManagementImpl();
         
      Constructor constructor = c.getDeclaredConstructor(new Class[] { });
      constructor.setAccessible(true);
      Object impl = constructor.newInstance(new Object[] { });
       
      Method m = c.getDeclaredMethod("getProcessId", new Class[] { });
      m.setAccessible(true);
      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.