记一次平时工作遇到的小问题

2019-03-11  本文已影响0人  我我我不是明

工作上看到一个小伙伴遇到一个场景,假设我有一个接收参数的类,里面包含参数{bookName, money, wan}

参数类

需要达到的目的是把这一个对象里面的3个参数,分别变成3个book的集合 List<Book> resultList

目的List<Book> resultList里面 第一个BookA里面只含有bookName参数

                                                第二个BookB里面只含有money参数 

                                                第三个BookC里面只含有wan参数

需要写个通用方法:目前我仅仅只判断了类里面的属性是String还是Integer,因为我不想一个一个else if去判断属性类型,我也在想办法优化一下;代码的话在最下面.自己新建一个类,拷贝下面的全部代码放到类里面就能运行

public static void main(String[] args) throws Exception{

    Object o =222333;

    Book book =new Book();

    book.setBookName("xiaowan");

    book.setMoney(250);

    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(book);

    PropertyValue propertyValue =new PropertyValue("wan", "aaaa");

    bw.setPropertyValue(propertyValue);

    List<Book> resultList =getEntity(book);

    resultList.stream().forEach(x-> System.out.println(x));

}

/**

* @descriptor 暂时还不是很完美,如果实体类里有其他类型需要过滤

* @author wbm

* @version 1.0

* @return

* @throws Exception

*/

public static <T> List<T> getEntity(T t) throws Exception{

    List<T> resultList =new ArrayList<>(10);

    Class<T> clazz =(Class<T>) t.getClass();

    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());

    for (PropertyDescriptor p : pds) {

        if (!p.getName().equals("class")) {

            Method readMethod = p.getReadMethod();

            String o = String.valueOf(readMethod.invoke(t, null));

            if (!StringUtils.isEmpty(o) && !o.equals("null")) {

                T result = clazz.newInstance();

                Field field = clazz.getDeclaredField(p.getName());

                ReflectionUtils.makeAccessible(field);

                Type fieldType = field.getGenericType();

                if (fieldType.toString().equals("class java.lang.String")) {

                    field.set(result, o);

                } else if (fieldType.toString().equals("class java.lang.Integer")) {

                    // 严谨一点可以判断转成int类型是否超过最大值Integer.MAX_VALUE

                    field.set(result, Integer.valueOf(o));

                } else {

                    System.out.println("出现错误啦");

                }

                resultList.add(result);

            }

}

}

    return resultList;

}

上一篇 下一篇

猜你喜欢

热点阅读