Beanutils工具包设置和读取JavaBean的属性
1、先把工具包的类导入进来,名字commons-beanutils-current.zip
2、加jar包,
a,工程右键,Build Path选择Configure Buile Path...选项卡为Libraries,Add External JARs...增加外面的jar包,这种方法是加在自己的目录下,没在工程内部,别人不能用。
b,在工程建立一个lib目录,放所有类库
把jar包拷贝到目录下
点击jar包右键->Build Path-〉Add to Build Path
3、还要用到日志开发包,apache提供的日志包
commons-logging.zip
方法一
Object value=7;//不为变量没法设
setProperties(pt1, prpertyName, value);
//上边set过属性,现在用工具
System.out.println(BeanUtils.getProperty(pt1, "x").getClass().getName());//结果的类型
/*
* x设置的时候是int类型的
* 但在beanUtils里设置的时候要用字符串,返回的也用String
* beanUtils可以自动进行类型转换
*/
BeanUtils.setProperty(pt1, "x", "9");
System.out.println(pt1.getX());
方法二
操作Date对象
/*
操作Date对象
date类型有个setTime的方法
birthday在ReflectPoint设置的
birthday是复合属性,不是基本属性,属性的类型是对象
把Date当成JavaBean来使用,setTime()当成time
这样就等于pt1上边的birthday的time对象赋值了
*/
BeanUtils.setProperty(pt1, "birthday.time()", "111");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time()"));//这样的好处是支持属性链
方法三:
BeanUtils工具不仅操作javaBean还可以操作map
Map map={name:"zxx",age:18};
BeanUtils.setProperty(map, "name", "lhm");
map的key相当于javaBean的属性
4、BeanUtils和PropertyUtils的区别
BeanUtils以字符串的形式对java进行操作,PropertyUtils不需要进行转换
//进行类型转换
BeanUtils.setProperty(pt1, "birthday.time()", "111");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time()"));//这样的好处是支持属性链
PropertyUtils.setProperty(pt1, "x", 9);
System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());//结果的类型
PropertyUtils.setProperty(pt1, "x", 9);
//不进行类型转化时
System.out
.println(PropertyUtils.getProperty(pt1, "x").getClass());