最近学了一个对javaBean进行操作的工具类。
程序中对javabean的操作很频繁,所以apache提供了一套开源的api,方便对javabean的操作!即BeanUtils组件。
BeanUtils组件, 作用是简化javabean的操作!
用户可以从www.apache.org下载BeanUtils组件,然后再在项目中引入jar文件!
使用BenUtils组件:
1. 引入commons-beanutils-1.8.3.jar核心包
2. 引入日志支持包: commons-logging-1.1.3.jar
1.javeBean 类
package entity;
public class admin {
private String name;
private String id;
private String phone;
public admin() {
super();
}
public admin(String name, String id, String phone) {
super();
this.name = name;
this.id = id;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "admin [name=" + name + ", id=" + id + ", phone=" + phone + "]";
}
}
2.BeanUtils工具类的使用
package Test;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import entity.admin;
public class test {
@Test
public void beanUtils() throws IllegalAccessException, InvocationTargetException{
admin ad=new admin();
//建立BeanUtils 对象
BeanUtils be=new BeanUtils();
//对admin对象进行操作
//一。类型都是String 类型
/**
* be.copyProperty(1,2,3);
* 1是 javeBean 的对象
* 2是javeBean 的私有变量
* 3是 你需要对2赋值的值
*
*/
be.copyProperty(ad, "name", "鼓励"); //复制
be.setProperty(ad,"id","123456"); //赋值
be.setProperty(ad,"phone","123456789");
//检验
System.out.println("-------------");
System.out.println("ad: "+ad.toString());
//二。对象的拷贝
/**
* be.copyProperties(newad,ad);
* newad 为新的对象
* ad 为原本对象
*/
admin newad=new admin();
be.copyProperties(newad, ad);
System.out.println("-------------");
System.out.println("newad: "+newad.toString());
//三。map 数据拷贝到javabean 对象中
/**
* BeanUtils.populate(adminMap, map);
* adminMap为javabean 的对象
*/
admin adminMap=new admin();
Map<String,String> map=new HashMap<String,String>();
map.put("name", "小明");
map.put("id", "123456");
map.put("phone","665464543");
be.populate(adminMap,map);
System.out.println("-------------");
System.out.println("adminMap: "+adminMap);
}
}
3.输出效果
-------------
ad: admin [name=鼓励, id=123456, phone=123456789]
-------------
newad: admin [name=鼓励, id=123456, phone=123456789]
-------------
adminMap: admin [name=小明, id=123456, phone=665464543]