Java Dynamic Management Kit 5.0 Tutorial

Implementing an MBean

The second part of an MBean is the class that implements the MBean interface. This class encodes the expected behavior of the manageable resource in its implementation of the attribute and operation methods. The resource does not need to reside entirely in this class. The MBean implementation can rely on other objects.

If the MBean must be instantiated remotely, it must be a concrete class and must expose at least one public constructor so that any other class can create an instance.

Otherwise, the developer is free to implement the management interface in any way, provided that the object has the expected behavior. Here is the sample code that implements our MBean interface:


Example 1–2 SimpleStandard Class

public class SimpleStandard implements SimpleStandardMBean {

     public String getState() {
        return state;
    }

    public void setState(String s) {
        state = s;
        nbChanges++;
    }

    public Integer getNbChanges() {
        return new Integer(nbChanges);
    }

    public void reset() {
        state = "initial state";
        nbChanges = 0;
        nbResets++;
    }

    // This method is not a getter in the management sense because 
    // it is not exposed in the "SimpleStandardMBean" interface.
    public Integer getNbResets() {
        return new Integer(nbResets);
    }

    // internal variables for exposed attributes
    private String      state = "initial state";
    private int         nbChanges = 0;

    // other private variables
    private int         nbResets = 0;   
}

As in this example, attributes are usually implemented as internal variables whose value is returned or modified by the getter and setter methods. However, an MBean can implement any access and storage scheme to fit particular management needs, provided getters and setters retain their read and write semantics. Methods in the MBean implementation can have side-effects, but it is up to you to ensure that these are safe and coherent within the full management solution.

As we will see later, management applications never have a direct handle on an MBean. They only have an identification of an instance and the knowledge of the management interface. In this case, the mechanism for exposing attributes through methods in the MBean interface makes it impossible for an application to access the MBean directly. Internal variables and methods, and even public ones, are totally encapsulated and their access is controlled by the programmer through the implementation of the MBean interface.