JavaBean存数据和Map存数据都是通过KV对的形式
JavaBean是属性名和属性值
Map是key值对应value值
都是唯一的属性名和唯一的key值
可以看成都是KV对形式
见如下演示-->
pojo类
public class Student {
/**
* 自定义字段
*/
String name;
int age;
/**
* 无参构造器
*/
public Student(){}
/**
* 定义有参构造器
* 默认无参构造器失效
*/
public Student(String aName,int aAge){
name = aName;
age = aAge;
}
/**
* 自定义方法
*/
public void sayHi(){
System.out.println("你们好,我是" + name);
System.out.println("今年:" + age);
System.out.println("-------------");
}
/**
* setter 和 getter 方法
*/
public void setName(String aName){
name = aName;
}
public String getName(){
return name;
}
public void setAge(int Aage){
age = Aage;
}
public int getAge(){
return age;
}
/**
* 自定义方法2
*/
public void learn(String course){
System.out.println(name + "今天学习了"+course+"课") ;
}
/**
* 覆盖toString方法
* @return
*/
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
写个Map转JavaBean的工具类
/**
* map和javabean的转换
*/
public class Map2JavaBeanUtils {
// 无参构造
public Map2JavaBeanUtils() {
}
// 返回一个bean对象用object来代替
// 传参要指定类型,因为不知道bean对象Object是什么类型的
// 对clz对象进行内省,获取bean的信息
public static Object map2Bean(Map<Object,Object> map,Class clz) throws Exception{
// 用字节码去创建对象
Object obj = clz.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
// 遍历
for (PropertyDescriptor pd : propertyDescriptors) {
String key = pd.getName();
Method writeMethod = pd.getWriteMethod();
// 在Map里面取拿想要的参数
Object value = map.get(key);
// 把值设置到value对象上
writeMethod.invoke(obj,value);
}
return obj;
}
}
测试类
public class Map2BeanTest {
// 也可以通过mock的方式
@Test
public void test_utils() throws Exception {
HashMap<Object, Object> map = new HashMap<>();
map.put("name","古天乐");
map.put("age",18);
Object map2Bean = Map2JavaBeanUtils.map2Bean(map, Student.class);
System.out.println(map2Bean);
}
}