admin@glassfish.java.net

Re: trying to use method.invoke() on MXBean

From: Eamonn McManus <Eamonn.McManus_at_Sun.COM>
Date: Fri, 05 Sep 2008 10:10:50 +0200
Jennifer,

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.)

Regards,
Éamonn McManus · JMX Spec Lead · http://weblogs.java.net/blog/emcmanus/


Jennifer Chou wrote:
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