自定义一个BeanUtils工具类
- 定义一个静态的工具类,定义的方法为populate,参数为
Object和Map
package Day01_Demo.Test06;/*@create 2020--12--21--14:56*/import org.apache.commons.beanutils.BeanUtils;import java.lang.reflect.InvocationTargetException;import java.util.Map;public class MyBeanUtils {//自动填充public static void populate(Object bean,Map<String,String[]> properties) {try {BeanUtils.populate(bean, properties);} catch (IllegalAccessException | InvocationTargetException e) {//作为运行时异常抛出,因为当前这个类是工具类,其他类调用的时候就不需要再处理异常了throw new RuntimeException(e);}}//自动填充的方法,并且返回bean对象public static Object populate(Class beanClass, Map<String, String[]> properties) {try {Object bean = beanClass.newInstance();//填充数据BeanUtils.populate(bean, properties);return bean;} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {//将编译时异常,转换成运行时异常,方便调用者(使用者就不需要再处理异常了)throw new RuntimeException(e);}}}
测试类
package Day01_Demo.Test06;/*@create 2020--12--21--15:06*/import Day01_Demo.Test05.User;import org.junit.Test;import java.util.HashMap;import java.util.Map;/*** 测试自定义的方法 - populate*/public class MyBeanUtilsTest {@Testpublic void test1() {Map<String, String[]> map = new HashMap<>();map.put("uid", new String[]{"u007"});map.put("username", new String[]{"王语嫣","段誉"});map.put("password", new String[]{"111"});//2.使用populateUser user = new User();MyBeanUtils.populate(user, map);//不需要抛异常,因为已经处理了System.out.println(user);}@Testpublic void test2() {Map<String, String[]> map = new HashMap<>();map.put("uid", new String[]{"u007"});map.put("username", new String[]{"王语嫣","段誉"});map.put("password", new String[]{"111"});//2.使用populate方法进行统一的填写 - 向下转型 - 因为自己封装的方法返回的是Object类型,所以// 如果要获取指定的类型就必须向下转型User user = (User) MyBeanUtils.populate(User.class, map);System.out.println(user);}}
