JavaBean的复杂内省操作

本文通过一个Java示例介绍了如何使用反射获取和设置对象属性,并对比了BeanUtils和PropertyUtils的不同用法。

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

public static void main(String[] args) throws Exception {
  ReflectPoint reflect = new ReflectPoint(3, 5);
  String propertyName = "x";
  PropertyDescriptor propertyDescript = new PropertyDescriptor(propertyName, reflect.getClass());

   //获得get方法
  Method methodGet = getProperty(reflect, propertyName);
  Object retval = methodGet.invoke(reflect);
  System.out.println(retval);

  //获得set方法
  Method methodWrite= propertyDescript.getWriteMethod();
  methodWrite.invoke(reflect,7);
  System.out.println(methodGet.invoke(reflect));
 }

 

BeanUtil 工具使用

要用的jar包:

commons-beanutils

commons-logging

使用:

 BeanUtils.setProperty(reflect, "x", "9");
  System.out.println(BeanUtils.getProperty(reflect, propertyName)); 
  //它们之间的差别BeanUtils传递参数类型是String类型,而PropertyUtils传递参数类型是和java类里的类型相同可以作用于Map里
  PropertyUtils.setProperty(reflect, "x", 11);
  System.out.println(PropertyUtils.getProperty(reflect, propertyName));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值