private void init(){ className = this.getClass().getName(); description = "Simple implementation of a dynamic MBean."; attributes = new MBeanAttributeInfo[1]; constructors = new MBeanConstructorInfo[1]; operations = new MBeanOperationInfo[1]; mBeanNotificationInfoArray = new MBeanNotificationInfo[0]; }
private void buildDynamicMBean(){ Constructor[] thisConstructors = this.getClass().getConstructors(); constructors[0] = new MBeanConstructorInfo("HelloDynamic(): Constructs a HelloDynamic Object",thisConstructors[0]);
attributes[0] = new MBeanAttributeInfo("name","java.lang.String","Name:name string.",true,true,false);
MBeanParameterInfo[] params = null; operations[0] = new MBeanOperationInfo("print","print():print the name",params,"void",MBeanOperationInfo.INFO); mBeanInfo = new MBeanInfo(className,description,attributes,constructors,operations,mBeanNotificationInfoArray); }
public HelloDynamic(){ init(); buildDynamicMBean(); }
private void dynamicAddOperation(){ init(); operations = new MBeanOperationInfo[2]; buildDynamicMBean(); operations[1] = new MBeanOperationInfo("print1","print1():print the name",null,"void",MBeanOperationInfo.INFO); mBeanInfo = new MBeanInfo(className,description,attributes,constructors,operations,mBeanNotificationInfoArray); }
@Override public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if (attribute == null) { return null; } if (attribute.equals("Name")) { return name; }
return null; }
@Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (attribute == null) { return; }
String Name = attribute.getName(); Object value = attribute.getValue();
try { if (Name.equals("Name")) { if (value == null) { name=null; } else if (Class.forName("java.lang.String").isAssignableFrom(value.getClass())) { name = (String) name; } } } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public class HelloAgent { public static void main(String[] args) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName helloName = new ObjectName("MyMBean:name=helloDynamic"); HelloDynamic hello = new HelloDynamic(); server.registerMBean(hello,helloName);
ObjectName adapterName = new ObjectName("MyMBean:name=htmladapter"); HtmlAdaptorServer adapter = new HtmlAdaptorServer(); server.registerMBean(adapter,adapterName); adapter.start(); } }
运行效果图如下:
运行结果:
Hello, null,this is HelloDynamic! 这是动态增加的一个方法print1