Example #1
0
  /**
   * 从一个对象提取另一个类型的值, 如: 从TransportOrderQe中提取父类TransportOrder, 以便送到服务器进行hibernate的持久化.
   *
   * @param fromObj
   * @param toClass
   * @return
   */
  public static Object extractObject(Object fromObj, Class toClass)
      throws InstantiationException, IllegalAccessException {
    if (fromObj == null || toClass == null) {
      return null;
    }
    Collection getters = ObjectUtil.getGetters(toClass);
    Object toObj = toClass.newInstance();
    for (Iterator iterator = getters.iterator(); iterator.hasNext(); ) {
      Method getter = (Method) iterator.next();
      String propertyName = ObjectUtil.getPropertyName(getter.getName());
      getter = getGetter(fromObj.getClass(), propertyName);
      try {
        // System.out.println(">>>prop name: " + propertyName + ", getter: " + getter);
        Method setter =
            toClass.getMethod(
                ObjectUtil.getSetterMethodName(propertyName), new Class[] {getter.getReturnType()});

        Object getterResult = getter.invoke(fromObj, new Object[0]);

        setter.invoke(toObj, new Object[] {getterResult});
      } catch (NoSuchMethodException ex) {
        continue;
      } catch (IllegalAccessException ex) {
        continue;
      } catch (InvocationTargetException ex) {
        continue;
      }
    }
    return toObj;
  }
Example #2
0
  public static void copyFields(Object from, Object to) {
    Collection getters = ObjectUtil.getGetters(from.getClass());

    for (Iterator iterator = getters.iterator(); iterator.hasNext(); ) {
      Method getter = (Method) iterator.next();

      String propertyName = ObjectUtil.getPropertyName(getter.getName());

      try {
        Method setter =
            to.getClass()
                .getMethod(
                    ObjectUtil.getSetterMethodName(propertyName),
                    new Class[] {getter.getReturnType()});

        Object getterResult = getter.invoke(from, new Object[0]);

        setter.invoke(to, new Object[] {getterResult});
      } catch (NoSuchMethodException ex) {
        continue;
      } catch (IllegalAccessException ex) {
        continue;
      } catch (InvocationTargetException ex) {
        continue;
      }
    }
  }
Example #3
0
 /** --------- 将所有的字段设为null ------------ */
 public static void emptyFields(Object obj) {
   Collection setters = ObjectUtil.getSetters(obj.getClass());
   for (Iterator iterator = setters.iterator(); iterator.hasNext(); ) {
     Method setter = (Method) iterator.next();
     try {
       Class[] paramCls = setter.getParameterTypes();
       if (paramCls[0] == boolean.class) {
         //
         setter.invoke(obj, new Object[] {Boolean.FALSE});
       } else {
         setter.invoke(obj, new Object[] {null});
       }
     } catch (IllegalAccessException ex) {
       continue;
     } catch (InvocationTargetException ex) {
       continue;
     }
   }
 }