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

  • 相关阅读:
    网络资源
    为什么MVC不是一种设计模式? ---比较Backbone和Ext4.x在MVC实现上的差异
    Developing Backbone.js Applications
    【实例】爬虫:下载图片
    scheme语言编写执行
    HDU 4403 A very hard Aoshu problem (DFS暴力)
    【Python】输出程序运行的百分比
    SQL_字符操作函数
    Linux mm相关的问题
    java中Volatile修饰符的含义
  • 原文地址:https://www.cnblogs.com/rmsSpring/p/BeanUtil.html
Copyright © 2011-2022 走看看