Пример #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;
  }
Пример #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;
      }
    }
  }