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. Of course, the resource does not need to reside entirely in this class, the MBean implementation can rely on other objects.
Beyond the implementation of the corresponding MBean interface, there are two requirements on the MBean class:
It must be a concrete class so that it can be instantiated
It 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 of course that the object has the expected behavior. Here is the sample code that implements our MBean interface:
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; } |
In this example there is no constructor. Since the Java compiler provides a public, no-argument constructor by default in such cases, this is a valid MBean.
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 may 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 may have side-effects, but it is up to the programmer to insure that these are safe and coherent within the full management solution.
As we shall 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.