JavaBean与Map相互转化

1.添加依赖


	commons-beanutils
	commons-beanutils
	1.9.2


2.JavaBean转化为Map

        PersonBean person = new PersonBean();
        person.setAge(12);
        person.setGender("mail");
        person.setName("Tom");
        Map map = PropertyUtils.describe(person);

        for (Map.Entry entry : map.entrySet()) {
        	System.out.println(entry.getKey() + ": " + entry.getValue());
        }
            结果为:

age: 12
name: Tom
class: class com.mycompany.app.PersonBean
gender: mail


2.Map转化为JavaBean

        PersonBean person = new PersonBean();
        Map map = new HashMap();
        map.put("name", "Mike");
        map.put("age", new Integer(25));
	map.put("gender", "male");

        BeanUtils.populate(person, map);
        
        System.out.println("name: " + person.getName());
        System.out.println("age: " + person.getAge());
        System.out.println("gender: " + person.getGender());
               结果为:

name: Mike
age: 25
gender: male


你可能感兴趣的:(java)