commons-beanutil简化了内省的操作,底层使用的是内省
所需要的jar包:commons-beanutils.jar,commons-logging.jar
public class Student { private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", password=" + password + "]"; } }
public class Demo { public static void main(String[] args) throws Exception { fun2(); } public static void fun1() throws Exception { String className = "com.sflik.entity.Student"; Class c = Class.forName(className); Object stu = c.newInstance(); //作用一:给javabean对象属性赋值 BeanUtils.setProperty(stu, "id", 1); BeanUtils.setProperty(stu, "name", "zhsangsan"); BeanUtils.setProperty(stu, "password", "123456"); //作用二:获取javabean对象属性值 Object id = BeanUtils.getProperty(stu, "id"); Object name = BeanUtils.getProperty(stu, "name"); Object password = BeanUtils.getProperty(stu, "password"); System.out.println(id +" "+name+" "+password); } public static void fun2() throws Exception { //作用三:把map中的数据映射到javabean中 Map<String,Object> map = new HashMap<String,Object>(); map.put("id", 33); map.put("name", "lisi"); map.put("password", "2222"); Student stu = new Student(); BeanUtils.populate(stu, map); System.out.println(stu); } }