BeanUtils
BeanUtils的概述和简单使用
BeanUtils概述
BeanUtils是Apache commons组件的成员在之一,主要用于简化JavaBean封装数据的操作。它可以给JavaBean封装成一个字符串数据,也可以将一个表单提交的所有数据封装到JavaBean中。
需要的jar包
BeanUtils工具常用工具类有两个:BeanUtils,ConvertUtils。BeanUtils用于封装数据,ConvertUtils用于处理类型转换。
常用方法:
setProperty(Object obj,String name,Object value) 设置属性值,如果指定属性不存在,不抛异常。
getProperty(Object obj,String name) 获取属性值,如果指定属性不存在,抛方法找不到异常
代码案例:
public class BeanUtilsDemo {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
//Person persion = new Person("Jack", "22");
Person person=new Person();
System.out.println("封装前"+person);
//使用BeanUtils的setProperty设置属性值
BeanUtils.setProperty(person,"name","Jack");
BeanUtils.setProperty(person,"age","22");
System.out.println("封装后"+person);
//使用BeanUtils的getProperty获取属性值
System.out.println("name:"+BeanUtils.getProperty(person,"name"));
}
}
运行结果:
封装前List.Person@677327b6
封装后List.Person@677327b6
name:Jack
BeanUtils的populate放的使用
方法说明
BeanUtils类的populated(Object bean,Map<String,String[]> properties):将Map数据封装到指定JavaBean中,一般用于将表单的所有数据封装到JavaBean中。
代码案例,使用populated方法将数据封装到User对对象中:
public class BeanUtilsDemo2 {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
HashMap<String, String[]> map = new HashMap<String, String[]>();
map.put("name",new String[]{"Jack"});
map.put("age",new String[]{"22"});
//使用populate方法进行填充
Person person = new Person();
BeanUtils.populate(person,map);
System.out.println(person.getName()+":"+person.getAge());
}
}
BeanUtils自定义工具类
自定义工具类的基本使用
自定义一个静态工具类,定义方法populate,参数为Object和Map<String,String[]>,返回值类型为void。方便自己在实际开发中使用。
代码案例:
public class PopulateDemo {
public static Object populate(Class beanClass, Map<String,String[]> properties){
Object bean=null;
try {
bean=beanClass.newInstance();
BeanUtils.populate(bean,properties);
return bean;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return bean;
}
}