Javabean学习纪要
学习纪要
下面例子创建一个javabean工具用来将map中的数据写入到javabean中。
package cn.dl.fanshe; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; public class CommonTools { /* * 该方法用来将map中的数据写入javabean中 * */ public static <T> T beanUtil(Map map, Class<T> clazz){ T bean; try { bean = clazz.newInstance();//实例化javabean类 BeanUtils.populate(bean, map);//将map中的值写入bean中 return bean; } catch (Exception e) { throw new RuntimeException(e); } } } //测试类 package cn.dl.fanshe; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; public class TestCommonTools { @Test public void fun() throws Exception{ Class clazz = Class.forName("cn.dl.fanshe.User");//获取User类 Map<String , String> map= new HashMap<String,String>();//创建map map.put("username", "张三");//map中的键名要与User类中的属性名一致 map.put("password", "123456"); CommonTools ct = new CommonTools();//创建javabean工具类 System.out.println(ct.beanUtil(map, clazz));//调出工具类中的方法 } }
//User类
package cn.dl.fanshe;
public class User {
private String username;
private String password;
public User() {
super();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}