zoukankan      html  css  js  c++  java
  • JAVA BeanUtil应用 一个类向另一个类转换

    两个具有相同属性的pojo(对象)类相互转换。或父类向子类转换。

    定义方法类MyBeanUtil 如下:

    类MyBeanUtil 继承原有类BeanUtils

    public class MyBeanUtil extends BeanUtils {
     protected static Format format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     
     public static void populate(Object bean, Map properties)
       throws IllegalAccessException, InvocationTargetException {
      // Do nothing unless both arguments have been specified
      if ((bean == null) || (properties == null)) {
       return;
      }
      // Loop through the property name/value pairs to be set
      Iterator names = properties.keySet().iterator();
      while (names.hasNext()) {
       String name = (String) names.next();
       // Identify the property name and value(s) to be assigned
       if (name == null) {
        continue;
       }
       Object value = properties.get(name);
       try {
        Class clazz = PropertyUtils.getPropertyType(bean, name);
        if (null == clazz) {
         continue;
        }
        String className = clazz.getName();
        if (className.equalsIgnoreCase("java.util.Date")) {
         if (value == null || value.equals("")) {
          continue;
         } else if(value.toString().length()==10) {
          setProperty(bean, name, (java.util.Date)format.parseObject((String) value+" 00:00:00"));
          continue;
         }else {
          setProperty(bean, name, (java.util.Date)format.parseObject((String) value));
          continue;
         }
        }
        setProperty(bean, name, value);
       } catch (Exception e) {
        continue;
       }
      }

     }
    }

    使用方法:

    MyBeanUtil.populate(stoVO,MyBeanUtil.describe(sto));

    stoVO:子类对象

    sto:父类对象

    在页面显示时,如果需要显示视图值。可以再stoVO类中写。

  • 相关阅读:
    【BZOJ】1552/3506 [Cerc2007]robotic sort
    【BZOJ】1014 [JSOI2008]火星人prefix
    【BZOJ】1500: [NOI2005]维修数列
    【51NOD-0】1046 A^B Mod C
    【51NOD-0】1019 逆序数
    【51NOD-0】1018 排序
    【51NOD-0】1012 最小公倍数LCM
    The Grove(poj 3182)
    Iahub and Permutations(codeforces 314c)
    多边形之战(bzoj 2927)
  • 原文地址:https://www.cnblogs.com/rmsSpring/p/BeanUtil.html
Copyright © 2011-2022 走看看