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

  • 相关阅读:
    基于jquery的提示框JavaScript 插件,类Bootstrap
    css重点知识和bug解决方法
    小白初识js
    动态的将数据生成“表格”(京东商品),并具备搜索筛选工能
    原装js轮播图,鼠标移入停止轮播,移出继续轮播
    用js写九九乘法表格,附带背景颜色
    用js写直角三角形,等腰三角形,菱形
    关于两数组,求出两数组中相同的的对象
    好的js书写习惯
    前端之道
  • 原文地址:https://www.cnblogs.com/rmsSpring/p/BeanUtil.html
Copyright © 2011-2022 走看看