Exemplo n.º 1
0
  /**
   * Convert {@code Object} value to a value of the specified class type.
   *
   * @param value {@code Object} value to convert.
   * @param type conversion type.
   * @param <T> converted value type.
   * @return value converted to the specified class type.
   */
  public static <T> T convertValue(Object value, Class<T> type) {
    if (!type.isInstance(value)) {
      // TODO: Move string value readers from server to common and utilize them here
      final Constructor constructor =
          AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
      if (constructor != null) {
        try {
          return type.cast(constructor.newInstance(value));
        } catch (Exception e) {
          // calling the constructor wasn't successful - ignore and try valueOf()
        }
      }

      final Method valueOf =
          AccessController.doPrivileged(ReflectionHelper.getValueOfStringMethodPA(type));
      if (valueOf != null) {
        try {
          return type.cast(valueOf.invoke(null, value));
        } catch (Exception e) {
          // calling valueOf wasn't successful
        }
      }

      // at this point we don't know what to return -> return null
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.warning(
            LocalizationMessages.PROPERTIES_HELPER_GET_VALUE_NO_TRANSFORM(
                String.valueOf(value), value.getClass().getName(), type.getName()));
      }

      return null;
    }

    return type.cast(value);
  }