Because the MBean description should never change, it is usually created one time only at instantiation, and the getMBeanInfo method simply returns its reference at every call. The MBean constructor should therefore build the MBeanInfo object from the MBean metadata classes such that it accurately describes the management interface. And since most dynamic MBeans will always be instantiated with the same management interface, building the MBeanInfo object is fairly straightforward.
Example 2–2 shows how the SimpleDynamic MBean defines its management interface, as built at instantiation and returned by its getMBeanInfo method:
// class constructor public SimpleDynamic() { buildDynamicMBeanInfo(); } // internal variables describing the MBean private String dClassName = this.getClass().getName(); private String dDescription = "Simple implementation of a dynamic MBean."; // internal variables for describing MBean elements private MBeanAttributeInfo[] dAttributes = new MBeanAttributeInfo[2]; private MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1]; private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1]; private MBeanInfo dMBeanInfo = null; // internal method private void buildDynamicMBeanInfo() { dAttributes[0] = new MBeanAttributeInfo( "State", // name "java.lang.String", // type "State: state string.", // description true, // readable true); // writable dAttributes[1] = new MBeanAttributeInfo( "NbChanges", "java.lang.Integer", "NbChanges: number of times the State string has been changed.", true, false); // use reflection to get constructor signatures Constructor[] constructors = this.getClass().getConstructors(); dConstructors[0] = new MBeanConstructorInfo( "SimpleDynamic(): No-parameter constructor", //description constructors[0]); // the contructor object MBeanParameterInfo[] params = null; dOperations[0] = new MBeanOperationInfo( "reset", // name "Resets State and NbChanges attributes to their initial values", // description params, // parameter types "void", // return type MBeanOperationInfo.ACTION); // impact dMBeanInfo = new MBeanInfo(dClassName, dDescription, dAttributes, dConstructors, dOperations, new MBeanNotificationInfo[0]); } // exposed method implementing the DynamicMBean.getMBeanInfo interface public MBeanInfo getMBeanInfo() { // return the information we want to expose for management: // the dMBeanInfo private field has been built at instantiation time, return(dMBeanInfo); } |