Use a Dynamic MBean Façade Pattern

Much of the code for a dynamic MBean is similar from one dynamic MBean to another. Hence, there are two primary tasks on which to focus:

  • Creating metadata to describe each feature of the MBean

  • Implementing the DynamicMBean interface

Dynamic MBean metadata classes are immutable, so the only way to set their various properties is to use a constructor. In addition, a metadata class must be created—and code written—for every feature on the management interface of a resource, resulting in lots of code that basically looks the same. A simplified approach to creating dynamic MBean metadata would help to reduce code clutter (and hence, readability). Here is an example of how to create a dynamic MBean metadata class for an attribute called MyAttribute of type Integer that is read-only:

MBeanAttributeInfo attribute = new MBeanAttributeInfo(
  "MyAttribute",            // Name
  Integer.class.getName(  ),  // Type
  "My very own attribute.", // Description
  true,                     // Is Readable?
  false,                    // Is Writeable?
  false);                   // isIs (i.e., is boolean?)

Of course, you could have squeezed all the parameters onto one line of code, but that would sacrifice readability (and could introduce errors). For example, JMX will allow you to create incorrect metadata for the attribute we just looked at:

MBeanAttributeInfo attribute = new MBeanAttributeInfo(
  "MyAttribute",            // Name
  Long.class.getName(  ), // Type "My very own attribute.", // Description true, // Is Readable? false, // Is Writeable? false); // ...

Get Java Enterprise Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.