本文共 3633 字,大约阅读时间需要 12 分钟。
由于对属性设置值和得到值的需求很多,使用频率很高,所以有一些开源勇士 不满足于JavaBean API 中IntroSpector来操作bean,
写出来了通用的BeanUtils工具,来进一步简化对java bean的操作,并开源放在apache网站上提供免费下载。
Beanutils工具包
1 commons-beanutils-1.9.2-bin.zip 2 commons-beanutils-1.9.2-src.zip 3 commons-logging-1.1.3-bin.zip 4 commons-logging-1.1.3-src.zip
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 缺少logging的jar包
这个日志包,很多框架都在用。
这非常适合浏览器传过来的字符串对对象进行set。
java bean
package com.itcast.day1;import java.util.Date;public class ReflectPoint { private Date birthday=new Date(); private int x; public int y; public ReflectPoint(int x, int y) { super(); this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ReflectPoint other = (ReflectPoint) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "ReflectPoint [birthday=" + birthday + ", x=" + x + ", y=" + y + "]"; } }
开始做,坚持做,重复做测试类:
package com.itcast.day2;import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.PropertyUtils;import com.itcast.day1.ReflectPoint;public class IntroSpectorTest { public static void main(String[] args) throws Exception{ ReflectPoint rf1=new ReflectPoint(3,4); Object value=6; System.out.println(BeanUtils.getProperty(rf1, "x").getClass().getName());// x是int,但是用beanutils设值时为 System.out.println(rf1.getX()); BeanUtils.setProperty(rf1, "x",1); //原来类型 设值 BeanUtils.(rf1, "x","2"); //支持String类型 设值 System.out.println(rf1.getX()); BeanUtils.setProperty(rf1, "birthday.time", "111");//支持属性级联操作 System.out.println(BeanUtils.(rf1, "birthday.time").getClass().getName());//java.lang.String 111 Map mm=BeanUtils.(rf1);//javabean转成map System.out.println(rf1);//ReflectPoint [birthday=Thu Jan 01 08:00:00 GMT+08:00 1970, x=2, y=4] Map map=new HashMap(); map.put("x", 1); map.put("y",1); BeanUtils.(rf1, map);//把map转换成javabean System.out.println(rf1);//ReflectPoint [birthday=Thu Jan 01 08:00:00 GMT+08:00 1970, x=1, y=1] //PropertyUtils.setProperty(rf1, "x", "9");//运行出错!因为PropertyUtils只支持原来的类型,这点没有BeanUtils强大! PropertyUtils.setProperty(rf1, "x", 9); System.out.println(rf1.getX());//9 }}
转载地址:http://lbovx.baihongyu.com/