package cn.code.domain; public class Person { private String name; private int age; private String gender; @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", gender=" + gender + "]"; } public Person() { super(); // TODO Auto-generated constructor stub } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Person(String name, int age, String gender) { super(); this.name = name; this.age = age; this.gender = gender; } }
package cn.code.domain; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; public class Demo1 { @Test public void fun1() throws Exception{ String className = "cn.code.domain.Person"; Class clazz = Class.forName(className); Object p = clazz.newInstance(); BeanUtils.setProperty(p, "name", "张三"); BeanUtils.setProperty(p, "age", "23"); BeanUtils.setProperty(p, "gender", "boy"); System.out.println(p.toString()); } @Test public void fun2() throws Exception{ Map<String,String>map = new HashMap<String, String>(); map.put("username", "killy"); map.put("password", "123"); User user = new User(); BeanUtils.populate(user, map); System.out.println(user); } }
package cn.code.domain; public class User { private String username; private int password; @Override public String toString() { return "user [username=" + username + ", password=" + password + "]"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getPassword() { return password; } public void setPassword(int password) { this.password = password; } public User() { super(); // TODO Auto-generated constructor stub } public User(String username, int password) { super(); this.username = username; this.password = password; } }
package cn.code.CommonUtils; import java.util.Map; import java.util.UUID; import org.apache.commons.beanutils.BeanUtils; public class CommonUtils { public static String uuid(){ return UUID.randomUUID().toString().replace("-","").toUpperCase(); } public static<T> T toBean(Map map,Class<T> clazz){ try{ T bean = clazz.newInstance(); BeanUtils.populate(bean,map); return bean; }catch(Exception e){ throw new RuntimeException(e); } } }
依赖jar包:apache_commons_beanUtils commmons_logging
时间: 2024-11-08 05:40:17