The problem is that the interface ClassLoadingMXBean is public but the implementation class sun.management.ClassLoadingImpl is not. This means that the method ClassLoadingMXBean.getLoadedClassCount() is accessible but the method sun.management.ClassLoadingImpl.getLoadedClassCount() is not. If you wrote ((sun.management.ClassLoadingImpl) clBean).getLoadedClassCount() instead of just clBean.getLoadedClassCount() then it would not compile, and reflection doesn't do anything different.
If you write
ClassLoadingMXBean.class.getMethod("getLoadedClassCount") then it
should work. (Because getMethod is varargs you don't need the second
argument.)
Hi,
I'm trying use method.invoke(..) on the MXBeans but I'm getting IllegalAccessException on some but not all the MXBeans. Anybody know why? And how to get around this problem?
java.lang.management.ClassLoadingMXBean clBean = ManagementFactory.getClassLoadingMXBean();
java.lang.reflect.Method method = clBean.getClass().getMethod("getLoadedClassCount", (Class[]) null);
method.invoke(clBean, (Object[]) null);
These get IllegalAccessException:
ClassLoadingMXBean
CompilationMXBean
GarbageCollectorMXBean
MemoryMXBean
MemoryMXBean
These allow me to use method.invoke():
OperatingSystemMXBean
MemoryUsage
Jennifer