JMX Dynamic MBean

本文深入探讨了Java管理扩展(JMX)中DynamicMBean的概念及其实现方式。文章详细介绍了DynamicMBean的特性,包括如何通过元数据定义管理接口,以及如何使用反射实现属性的获取与设置、操作的调用等关键功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    The second MBean I want to bring in is the Dynamic MBean, the main purpose of using Dynamic MBean is that your management interface varies very often, just think of a simplest case, we have a managed resource about the Person's information, and now we can set and get the firstName and lastName of a certain person thro jmx and it works fine, but one day, your boss tell you that we should provide the address info of the person too, if we're using the Standard MBean, what should we do? We have to modify the interface and add the implementations for added methods, don't we?It would be a mess of work when this kind of situation happens often, especially when the Standard MBean's management interface consists of many predefined interfaces which is prone to be changed later. And Dynamic MBean can ease this kind of situation(Although Dynamic MBean can ease this situation, it also has some limitations, which will be covered in Model MBean blog entry).

 

     Recall from the Standard MBean article, its management interface is made of some predefined interface the MBean implements, while Dynamic MBean forms its management interface by its metadata, a MBeanInfo.That's why the Dynamic MBean interface defines a 'getMBeanInfo()' method. Now let's take a look at the Dynamic MBean interface.



 

    There is a limitation about MBeas is that a MBean can not be both Standard and Dynamic, that is to say, a MBean can not implements the Standard interface and the Dynamic interface at the same time. As we previously described, the management interface is nothing but a group of attributes and operations, and that is why Dynamic MBean interface defines methods such as getAttribute(), setAttribute().

 

    Since we all know that the Daynamic MBean's management interface is defined at runtime, so, you would like to examine the MBeanInfo in Dynamic MBean, and see how it make up the management interface.

   


   MBeanFeatureInfo is the super class of all the other mbean metadatas. And from their names, we could easily infer their purposes, for example MBeanOperationInfo correponds to the operations defined in the manageable resource and the MBeanAttributeInfo corresponds to the attributes of your manageable resource. Although they are easy to understand, I still like to walk you through them one by one.

   Speaking of MBeanFeatureInfo, since it's the super class of all the other mbean metadatas, it only defines two attributes that need us to be awared of.

  • name->what does it stand for depends on the metadata type, if the metadata type is method-related, such as MBeanOperationInfo or MBeanConstructorInfo, then the name here indicates a method name, if the metadata type is attribute-related like MBeanParamenterInfo or MBeanAttributeInfo, then it indicates a attribute name.
  • description->a custom text which is used to describe what is this metadata for or something like that.

   MBeanParameterInfo, a parameter wrapper which is used in MBeanOperationInfo or MBeanConstructorInfo. You can create it in the following two ways:

 public MBeanParameterInfo(String name, String type,String description)

 public MBeanParameterInfo(String name,String type,String description,Descriptor descriptor)

    We'll avoid Descriptor class here, since it will be covered in Model MBean article. Here just think of it as an object that can hold some additional infos.

  •     type->the parameter type of course, for example, for parameter 'String name', its type is 'java.lang.String'

    MBeanOperationInfo, it encapsulates an operation exposed by an MBean, a method wrapper.The following are its two constructors:

   

public MBeanOperationInfo(String description, Method method);

public MBeanOperationInfo(String name,
			      String description,
			      MBeanParameterInfo[] signature,
			      String type,
			      int impact)
  • type->indicates the type of the return value of this method.
  • impact->there are four values for this argument,INFO,ACTION,ACTION_INFO and UNKNOWN.INFO means this operation can return information, ACTION indicates the operation could change the state of MBean without returning information, ACTION_INFO indicates the operation not only change the state of MBean but also return information, and UNKNOWN indicates an unknown operation.

   

    MBeanAttributeInfo, it can encapsulates an attribute of MBean, just like the other metadata, you can construct it in the following ways:

   

public MBeanAttributeInfo(String name,
			      String type,
			      String description,
			      boolean isReadable,
			      boolean isWritable,
			      boolean isIs)

 public MBeanAttributeInfo(String name,
			      String type,
			      String description,
			      boolean isReadable,
			      boolean isWritable,
			      boolean isIs,
                              Descriptor descriptor)
  • type->the type of attribute, like the one in MBeanParameterInfo.
  • isReadable->indicates whether it is readable or not.
  • isWritable->indicates whether it is writable or not.
  • isIs->indicates whether this attribute starts with 'is' or not, in the meantime, this attribute has to be a boolean type.

     MBeanConstructorInfo, a constructor wrapper, you can create it by using its two constructors:

  

public MBeanConstructorInfo(String description, Constructor constructor)

 public MBeanConstructorInfo(String name, 
			String description,
			MBeanParameterInfo[] signature)

  

   MBeanNotificationInfo, a metadata class that describes the notifications the MBean can emit. Nothing special and like the other metadata classes, it has two constructors:

  

public MBeanNotificationInfo(String[] notifTypes,
				 String name,
				 String description)

public MBeanNotificationInfo(String[] notifTypes,
			 String name,
			 String description,
                                 Descriptor descriptor)

 

   After examining the Dynamic MBean interface and its metadata classes, it is time for some concrete examples to combine them together. We often implement the Dynamic MBean by using javabean introspection, if you have experience of java reflection, you'll find that there are no fancy codes at all in the following codes.

  

public class DynamicImpl implements DynamicMBean {

	public Object getAttribute(String attribute)
			throws AttributeNotFoundException, MBeanException,
			ReflectionException {

		try {
			Field attr = this.getClass().getDeclaredField(attribute);
			// this make the private attribute accessible
			attr.setAccessible(true);
			return attr.get(this);
		} catch (Exception e) {
			// eatting all
		}
		return null;
	}

	public AttributeList getAttributes(String[] attributes) {
		AttributeList attrList = new AttributeList();
		try {
			Attribute attribute = null;
			for (String attr : attributes) {
				attribute = new Attribute(attr, getAttribute(attr));
				attrList.add(attribute);
			}
		} catch (Exception e) {
			// eatting all
		}
		return attrList;
	}

	public Object invoke(String actionName, Object[] params, String[] signature)
			throws MBeanException, ReflectionException {
		try {
			// first, constructing the param types
			Class[] paramTypes = new Class[signature.length];
			int i = 0;
			for (String sig : signature) {
				paramTypes[i++] = this.getClass().getClassLoader().loadClass(
						sig);
			}

			// find the method and invoke it
			Method md = this.getClass().getMethod(actionName, paramTypes);
			return md.invoke(this, params);
		} catch (Exception e) {
			// eatting all
		}
		return null;
	}

	public void setAttribute(Attribute attribute)
			throws AttributeNotFoundException, InvalidAttributeValueException,
			MBeanException, ReflectionException {
		try {
			Field attr = this.getClass().getDeclaredField(attribute.getName());
			// this make the private attribute accessible
			attr.setAccessible(true);
			attr.set(this, attribute.getValue());
		} catch (Exception e) {
			// eatting all
		}
	}

	public AttributeList setAttributes(AttributeList attributes) {
		try {
			Attribute attribute = null;
			for (int i = 0; i < attributes.size(); i++) {
				attribute = (Attribute) attributes.get(i);
				setAttribute(attribute);
			}
		} catch (Exception e) {
			// eatting all
		}
		return attributes;
	}

	public MBeanInfo getMBeanInfo() {
		// exposes the attribute name
		MBeanAttributeInfo attributeInfo = new MBeanAttributeInfo("name",
				"java.lang.String", "name exposed", true, true, false);

		// exposes the printName operation
		MBeanOperationInfo operationInfo = new MBeanOperationInfo("printName",
				"pring name info ", new MBeanParameterInfo[0], "void", 2);

		return new MBeanInfo("DynamicImpl",
				"The manageable resource is DynamicImpl",
				new MBeanAttributeInfo[] { attributeInfo },
				new MBeanConstructorInfo[0],
				new MBeanOperationInfo[] { operationInfo },
				new MBeanNotificationInfo[0]);
	}

	private String name;

	public void printName() {
		System.out.println("name->" + name);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

   When you finish your Dynamic MBean, register it to the MBean Server and enjoy it.

 

1. 用户与身体信息管理模块 用户信息管理: 注册登录:支持手机号 / 邮箱注册,密码加密存储,提供第三方快捷登录(模拟) 个人资料:记录基本信息(姓名、年龄、性别、身高、体重、职业) 健康目标:用户设置目标(如 “减重 5kg”“增肌”“维持健康”)及期望周期 身体状态跟踪: 体重记录:定期录入体重数据,生成体重变化曲线(折线图) 身体指标:记录 BMI(自动计算)、体脂率(可选)、基础代谢率(根据身高体重估算) 健康状况:用户可填写特殊情况(如糖尿病、过敏食物、素食偏好),系统据此调整推荐 2. 膳食记录与食物数据库模块 食物数据库: 基础信息:包含常见食物(如米饭、鸡蛋、牛肉)的名称、类别(主食 / 肉类 / 蔬菜等)、每份重量 营养成分:记录每 100g 食物的热量(kcal)、蛋白质、脂肪、碳水化合物、维生素、矿物质含量 数据库维护:管理员可添加新食物、更新营养数据,支持按名称 / 类别检索 膳食记录功能: 快速记录:用户选择食物、输入食用量(克 / 份),系统自动计算摄入的营养成分 餐次分类:按早餐 / 午餐 / 晚餐 / 加餐分类记录,支持上传餐食照片(可选) 批量操作:提供常见套餐模板(如 “三明治 + 牛奶”),一键添加到记录 历史记录:按日期查看过往膳食记录,支持编辑 / 删除错误记录 3. 营养分析模块 每日营养摄入分析: 核心指标计算:统计当日摄入的总热量、蛋白质 / 脂肪 / 碳水化合物占比(按每日推荐量对比) 微量营养素分析:检查维生素(如维生素 C、钙、铁)的摄入是否达标 平衡评估:生成 “营养平衡度” 评分(0-100 分),指出摄入过剩或不足的营养素 趋势分析: 周 / 月营养趋势:用折线图展示近 7 天 / 30 天的热量、三大营养素摄入变化 对比分析:将实际摄入与推荐量对比(如 “蛋白质摄入仅达到推荐量的 70%”) 目标达成率:针对健
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值