Esempio n. 1
0
  public static void copyPropertiesExceptNull(Object dest, Object orig)
      throws IllegalAccessException, InvocationTargetException {

    // Validate existence of the specified beans
    if (dest == null) {
      throw new IllegalArgumentException("No destination bean specified");
    }
    if (orig == null) {
      throw new IllegalArgumentException("No origin bean specified");
    }
    if (log.isDebugEnabled()) {
      log.debug("BeanUtils.copyProperties(" + dest + ", " + orig + ")");
    }

    // Copy the properties, converting as necessary
    BeanUtilsBean bub = BeanUtilsBean.getInstance();
    if (orig instanceof DynaBean) {
      DynaProperty[] origDescriptors = ((DynaBean) orig).getDynaClass().getDynaProperties();
      for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();
        // Need to check isReadable() for WrapDynaBean
        // (see Jira issue# BEANUTILS-61)
        if (bub.getPropertyUtils().isReadable(orig, name)
            && bub.getPropertyUtils().isWriteable(dest, name)) {
          Object value = ((DynaBean) orig).get(name);
          bub.copyProperty(dest, name, value);
        }
      }
    } else if (orig instanceof Map) {
      Iterator entries = ((Map) orig).entrySet().iterator();
      while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry) entries.next();
        String name = (String) entry.getKey();
        if (bub.getPropertyUtils().isWriteable(dest, name)) {
          bub.copyProperty(dest, name, entry.getValue());
        }
      }
    } else /* if (orig is a standard JavaBean) */ {
      PropertyDescriptor[] origDescriptors = bub.getPropertyUtils().getPropertyDescriptors(orig);
      for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();
        if ("class".equals(name) || "propName".equals(name) || "propValue".equals(name)) {
          continue; // No point in trying to set an object's class
        }
        if (bub.getPropertyUtils().isReadable(orig, name)
            && bub.getPropertyUtils().isWriteable(dest, name)) {
          try {
            Object value = bub.getPropertyUtils().getSimpleProperty(orig, name);
            if (value != null) {
              bub.copyProperty(dest, name, value);
            }
          } catch (NoSuchMethodException e) {
            // Should not happen
          }
        }
      }
    }
  }
Esempio n. 2
0
 /**
  * 拷贝属性给对象(类型宽松)
  *
  * @param bean
  * @param name 属性名
  * @param value 属性值
  */
 @SuppressWarnings({"unchecked", "rawtypes"})
 public static void copyProperty(Object bean, String name, Object value) {
   try {
     Class propertyClazz = BEANUTILSBEAN.getPropertyUtils().getPropertyType(bean, name);
     if (propertyClazz.isEnum() && value instanceof Integer) { // 属性枚举型 目标值是整型
       value = EnumUtils.getEnum(propertyClazz, (Integer) value);
     }
     BEANUTILSBEAN.copyProperty(bean, name, value);
   } catch (Throwable e) {
     LOGGER.error("BeanUtil 对象属性赋值出错:", e);
     throw new RuntimeException(e);
   }
 }
Esempio n. 3
0
 /** {@inheritDoc} 安静的拷贝属性,如果属性非法或其他错误则记录日志 */
 public boolean populateValue(
     final Object target, String entityName, final String attr, final Object value) {
   try {
     if (attr.indexOf('.') > -1)
       initProperty(target, entityName, Strings.substringBeforeLast(attr, "."));
     beanUtils.copyProperty(target, attr, value);
     return true;
   } catch (Exception e) {
     logger.warn(
         "copy property failure:[class:" + entityName + " attr:" + attr + " value:" + value + "]:",
         e);
     return false;
   }
 }
Esempio n. 4
0
 private void setValue(final String attr, final Object value, final Object target) {
   try {
     beanUtils.copyProperty(target, attr, value);
   } catch (Exception e) {
     logger.error(
         "copy property failure:[class:"
             + target.getClass().getName()
             + " attr:"
             + attr
             + " value:"
             + value
             + "]:",
         e);
   }
 }
Esempio n. 5
0
  /**
   * Implements the Contextualizable interface using bean introspection.
   *
   * @param aContext {@inheritDoc}
   * @throws CheckstyleException {@inheritDoc}
   * @see Contextualizable
   */
  public final void contextualize(Context aContext) throws CheckstyleException {
    final BeanUtilsBean beanUtils = createBeanUtilsBean();

    // TODO: debug log messages
    final Collection<String> attributes = aContext.getAttributeNames();

    for (final String key : attributes) {
      final Object value = aContext.get(key);

      try {
        beanUtils.copyProperty(this, key, value);
      } catch (final InvocationTargetException e) {
        // TODO: log.debug("The bean " + this.getClass()
        // + " is not interested in " + value)
        throw new CheckstyleException(
            "cannot set property "
                + key
                + " to value "
                + value
                + " in bean "
                + this.getClass().getName(),
            e);
      } catch (final IllegalAccessException e) {
        throw new CheckstyleException(
            "cannot access " + key + " in " + this.getClass().getName(), e);
      } catch (final IllegalArgumentException e) {
        throw new CheckstyleException(
            "illegal value '"
                + value
                + "' for property '"
                + key
                + "' of bean "
                + this.getClass().getName(),
            e);
      } catch (final ConversionException e) {
        throw new CheckstyleException(
            "illegal value '"
                + value
                + "' for property '"
                + key
                + "' of bean "
                + this.getClass().getName(),
            e);
      }
    }
  }
Esempio n. 6
0
  /**
   * 将map转Bean
   *
   * @param map
   * @param clazz
   * @return
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static Object buildBean(Map map, Class clazz) {
    if (map == null) {
      return null;
    }
    Object bean = null;
    try {
      bean = clazz.newInstance();
      PropertyDescriptor[] pds = BEANUTILSBEAN.getPropertyUtils().getPropertyDescriptors(clazz);
      for (PropertyDescriptor pd : pds) {
        String fieldName = pd.getName();
        if (map.containsKey(fieldName)) {
          Object mapValue = map.get(fieldName);
          Class beanType = pd.getPropertyType();
          Object beanValue = mapValue;

          if (beanType.isEnum()) {
            if (mapValue != null) {
              if (mapValue instanceof String) {
                if (String.valueOf(mapValue).matches("\\d+")) { // 数字型
                  mapValue = Integer.parseInt(String.valueOf(mapValue));
                  int intValue = (Integer) mapValue;

                  Method method = beanType.getMethod("values");
                  Object[] enumValues = (Object[]) method.invoke(beanType);
                  if (intValue >= 0 && intValue < enumValues.length) {
                    beanValue = enumValues[intValue];
                  } else {
                    continue;
                  }
                } else { // 字符串标识的枚举值
                  try {
                    beanValue = Enum.valueOf(beanType, String.valueOf(mapValue));
                  } catch (IllegalArgumentException e) { // 是一个错误的值
                    continue;
                  }
                }

              } else if (mapValue instanceof Integer) { // 整型
                int intValue = (Integer) mapValue;
                Method method = beanType.getMethod("values");
                Object[] enumValues = (Object[]) method.invoke(beanType);
                if (intValue >= 0 && intValue < enumValues.length) {
                  beanValue = enumValues[intValue];
                } else { // 超过了枚举的int值范围
                  continue;
                }
              }
            }
          } else if (beanType.equals(java.util.Date.class)) {
            if (mapValue != null) {
              if (mapValue instanceof String) {
                try {
                  DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  beanValue = format.parse(String.valueOf(mapValue));
                } catch (ParseException e) {
                  LOGGER.error("BeanHelper buildBean string 转 Date 出错!");
                  continue;
                }
              }
            }
          }

          BEANUTILSBEAN.copyProperty(bean, fieldName, beanValue);
        }
      }
      return bean;
    } catch (Throwable e) {
      LOGGER.error("BeanHelper 根据map创建bean出错:", e);
      throw new RuntimeException(e);
    }
  }
 @Override
 public void copyProperty(Object dest, String name, Object value)
     throws IllegalAccessException, InvocationTargetException {
   if (value == null) return;
   super.copyProperty(dest, name, value);
 }
Esempio n. 8
0
  /**
   * Implements the Configurable interface using bean introspection.
   *
   * <p>Subclasses are allowed to add behaviour. After the bean based setup has completed first the
   * method {@link #finishLocalSetup finishLocalSetup} is called to allow completion of the bean's
   * local setup, after that the method {@link #setupChild setupChild} is called for each {@link
   * Configuration#getChildren child Configuration} of <code>aConfiguration</code>.
   *
   * @param aConfiguration {@inheritDoc}
   * @throws CheckstyleException {@inheritDoc}
   * @see Configurable
   */
  public final void configure(Configuration aConfiguration) throws CheckstyleException {
    mConfiguration = aConfiguration;

    final BeanUtilsBean beanUtils = createBeanUtilsBean();

    // TODO: debug log messages
    final String[] attributes = aConfiguration.getAttributeNames();

    for (final String key : attributes) {
      final String value = aConfiguration.getAttribute(key);

      try {
        // BeanUtilsBean.copyProperties silently ignores missing setters
        // for key, so we have to go through great lengths here to
        // figure out if the bean property really exists.
        final PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(this, key);
        if ((pd == null) || (pd.getWriteMethod() == null)) {
          throw new CheckstyleException(
              "Property '"
                  + key
                  + "' in module "
                  + aConfiguration.getName()
                  + " does not exist, please check the documentation");
        }

        // finally we can set the bean property
        beanUtils.copyProperty(this, key, value);
      } catch (final InvocationTargetException e) {
        throw new CheckstyleException(
            "Cannot set property '"
                + key
                + "' in module "
                + aConfiguration.getName()
                + " to '"
                + value
                + "': "
                + e.getTargetException().getMessage(),
            e);
      } catch (final IllegalAccessException e) {
        throw new CheckstyleException(
            "cannot access " + key + " in " + this.getClass().getName(), e);
      } catch (final NoSuchMethodException e) {
        throw new CheckstyleException(
            "cannot access " + key + " in " + this.getClass().getName(), e);
      } catch (final IllegalArgumentException e) {
        throw new CheckstyleException(
            "illegal value '"
                + value
                + "' for property '"
                + key
                + "' of module "
                + aConfiguration.getName(),
            e);
      } catch (final ConversionException e) {
        throw new CheckstyleException(
            "illegal value '"
                + value
                + "' for property '"
                + key
                + "' of module "
                + aConfiguration.getName(),
            e);
      }
    }

    finishLocalSetup();

    final Configuration[] childConfigs = aConfiguration.getChildren();
    for (final Configuration childConfig : childConfigs) {
      setupChild(childConfig);
    }
  }