这是一个把Map转为bean的工具
导包
Bean代码,Student类
package com.lingaolu.bena;
/**
* @author 林高禄
* @create 2020-07-08-20:01
*/
public class Student {
private String name;
private int age;
private Integer no;
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 Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", no=" + no +
'}';
}
}
测试类代码Demo1
package com.lingaolu.test;
import com.lingaolu.bena.Student;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* @author 林高禄
* @create 2020-07-08-20:03
*/
public class Demo1 {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Map<String,Object> map = new HashMap<>();
map.put("name","林大帅");
map.put("age",27);
map.put("no",111);
Student s = new Student();
BeanUtils.populate(s,map);
System.out.println(s);
}
}
运行如果输出
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)
at org.apache.commons.beanutils.ContextClassLoaderLocal.get(ContextClassLoaderLocal.java:153)
at org.apache.commons.beanutils.BeanUtilsBean.getInstance(BeanUtilsBean.java:80)
at org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:433)
at com.lingaolu.test.Demo1.main(Demo1.java:23)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
缺少了 org/apache/commons/logging包
下载地址apache的logging包

解压
导入项目
再次运行输出:
Student{name='林大帅', age=27, no=111}
我们把测试再代码改一下
package com.lingaolu.test;
import com.lingaolu.bena.Student;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* @author 林高禄
* @create 2020-07-08-20:03
*/
public class Demo1 {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Map<String,Object> map = new HashMap<>();
map.put("name","林大帅");
map.put("age","234");
map.put("no","111");
Student s = new Student();
BeanUtils.populate(s,map);
System.out.println(s);
}
}
运行输出:
Student{name='林大帅', age=27, no=111}
所以对于数值来说,字符串或者数字都行
Map转Bean实用技巧
本文介绍了一种将Map数据结构转换为Java Bean对象的方法,使用Apache Commons BeanUtils库简化转换过程,展示了具体代码实例和常见错误处理。




877

被折叠的 条评论
为什么被折叠?



