javabean和map的相互转化

javabean和map之间的相互转化是工程中很常见的,转化的时候可以借助工具类, 分别是org.apache.commons.beanutils下的BeanUtils和net.sf.cglib.beans下的BeanMap

看下面一段代码

package commonsTest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import models.Student;
import models.Teacher;
import net.sf.cglib.beans.BeanMap;

import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;


public class Demo {
	/**
	 * 测试BeanUtils的populate方法,map转对象
	 */
	@Test
	public void Test1() throws Exception{
		Map map = new HashMap();
		map.put("name", "张三");
		map.put("addr", "北京");
		map.put("age", "1");
		Teacher t = new Teacher();
		Student s = new Student();
		BeanUtils.populate(t, map);
		BeanUtils.populate(s, map);
		ArrayList arrayList = new ArrayList();
		arrayList.add(s);
		t.setStudents(arrayList);
//		s.setTeacher(t);
		
		System.out.println(s);
		System.out.println(t);
		
		System.out.println(BeanMap.create(s));
		System.out.println(BeanMap.create(t));
	}
	
}
console展示的结果 :

javabean和map的相互转化_第1张图片
其中Student类和Teacher类如下

package models;

public class Student {
	private String name;
	private String addr;
	private Integer age;
	private Teacher teacher;
	public Teacher getTeacher() {
		return teacher;
	}
	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddr() {
		return addr;
	}
	public void setAddr(String addr) {
		this.addr = addr;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", addr=" + addr + ", age=" + age
				+ ", teacher=" + teacher + "]";
	}
	
}

package models;

import java.util.List;

public class Teacher {
	private String name;
	private Integer age;
	private String addr;
	public String getAddr() {
		return addr;
	}
	public void setAddr(String addr) {
		this.addr = addr;
	}
	private List students; 
	public String getName() {
		return name;
	}
	public List getStudents() {
		return students;
	}
	public void setStudents(List students) {
		this.students = students;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Teacher [name=" + name + ", age=" + age + ", addr=" + addr
				+ ", students=" + students + "]";
	}
	

}
值得注意的是, 测试类中有一行代码是注释掉的,因为如果Student对象中加入Teacher的引用, 会造成循环赋值, 转换会一致进行下去,直到爆内存


你可能感兴趣的:(java)