• 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类中写。

  • 相关阅读:
    POJ
    POJ-2253 Frogger(最短路)
    背包问题(转自背包九讲+对应题目)
    POJ-1860 Currency Exchange (最短路)
    Bellman-Ford 最短路径算法
    POJ-3295 Tautology (构造)
    POJ-2586 Y2K Accounting Bug 贪心
    POJ 2965 The Pilots Brothers' refrigerator (暴力枚举)
    python(pymysql操作数据库)
    python复习概念__oop中
  • 原文地址:https://www.cnblogs.com/rmsSpring/p/BeanUtil.html
Copyright © 2020-2023  润新知