1 package org.junit.internal.management; 2 3 import org.junit.internal.Classes; 4 5 import java.lang.reflect.InvocationTargetException; 6 7 /** 8 * Reflective wrapper around {@link java.lang.management.ManagementFactory} 9 */ 10 public class ManagementFactory { 11 private static final class FactoryHolder { 12 private static final Class<?> MANAGEMENT_FACTORY_CLASS; 13 14 static { 15 Class<?> managementFactoryClass = null; 16 try { 17 managementFactoryClass = Classes.getClass("java.lang.management.ManagementFactory"); 18 } catch (ClassNotFoundException e) { 19 // do nothing, managementFactoryClass will be none on failure 20 } 21 MANAGEMENT_FACTORY_CLASS = managementFactoryClass; 22 } 23 getBeanObject(String methodName)24 static Object getBeanObject(String methodName) { 25 if (MANAGEMENT_FACTORY_CLASS != null) { 26 try { 27 return MANAGEMENT_FACTORY_CLASS.getMethod(methodName).invoke(null); 28 } catch (IllegalAccessException e) { 29 // fallthrough 30 } catch (IllegalArgumentException e) { 31 // fallthrough 32 } catch (InvocationTargetException e) { 33 // fallthrough 34 } catch (NoSuchMethodException e) { 35 // fallthrough 36 } catch (SecurityException e) { 37 // fallthrough 38 } 39 } 40 return null; 41 } 42 } 43 44 private static final class RuntimeHolder { 45 private static final RuntimeMXBean RUNTIME_MX_BEAN = 46 getBean(FactoryHolder.getBeanObject("getRuntimeMXBean")); 47 getBean(Object runtimeMxBean)48 private static final RuntimeMXBean getBean(Object runtimeMxBean) { 49 return runtimeMxBean != null 50 ? new ReflectiveRuntimeMXBean(runtimeMxBean) : new FakeRuntimeMXBean(); 51 } 52 } 53 54 private static final class ThreadHolder { 55 private static final ThreadMXBean THREAD_MX_BEAN = 56 getBean(FactoryHolder.getBeanObject("getThreadMXBean")); 57 getBean(Object threadMxBean)58 private static final ThreadMXBean getBean(Object threadMxBean) { 59 return threadMxBean != null 60 ? new ReflectiveThreadMXBean(threadMxBean) : new FakeThreadMXBean(); 61 } 62 } 63 64 /** 65 * @see java.lang.management.ManagementFactory#getRuntimeMXBean() 66 */ getRuntimeMXBean()67 public static RuntimeMXBean getRuntimeMXBean() { 68 return RuntimeHolder.RUNTIME_MX_BEAN; 69 } 70 71 /** 72 * @see java.lang.management.ManagementFactory#getThreadMXBean() 73 */ getThreadMXBean()74 public static ThreadMXBean getThreadMXBean() { 75 return ThreadHolder.THREAD_MX_BEAN; 76 } 77 } 78