javajvmclassnotfoundexceptionibm-jvm

Why does this code compile, but with runtime ClassNotFoundException?


I have some code that uses the proprietary sun.*.OperatingSystemMXBean, so I was being careful with it.

try {
    _osBean = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
}
catch (ClassCastException e) {
    _osBean = null;
}

However, when this code runs on an IBM JVM, instead of ClassCastException, I get a runtime ClassNotFoundException. Why is this code able to compile just fine if that class is not available and how does a JVM affect something like this?


Solution

  • the com.sun.* packages are private classes written by sun for the sun JVM (hotspot) and are not public API (even though your code proves they are accessible). the IBM JVM is a completely different implementation and doesnt have them (as they are not part of any java/jvm spec).
    im guessing it compiles fine since youre compiling with the sun/oracle JDK
    to try and resolve the issue, try casting to

    java.lang.management.OperatingSystemMXBean
    

    instead (which is a public API) and see if that works for you