Exemplo n.º 1
0
  /** Coerces the object to the indicated type. */
  public static Object coerce(TemplateContext ctx, Class<?> type, final Object o) {
    Object arg;

    if (o != null && type == o.getClass()) {
      arg = o;
    } else if (type == String.class) {
      arg = Types.toString(ctx, o);
    } else if (type == int.class || type == Integer.class) {
      arg = Types.toInteger(ctx, o);
    } else if (type == long.class || type == Long.class) {
      arg = Types.toLong(ctx, o);
    } else if (type == float.class
        || type == Float.class
        || type == double.class
        || type == Double.class) {
      arg = Types.toDouble(ctx, o);
    } else if (type == boolean.class || type == Boolean.class) {
      arg = Types.toBoolean(ctx, o);
    } else if (type == Iterator.class) {
      arg = Types.toIterator(ctx, o);
    } else {
      if (o == null) {
        arg = null;
      } else {
        final Converter<Object, Object> converter = ctx.getConverter(o.getClass(), type);
        if (converter == null) {
          arg = o;
        } else {
          try {
            arg = converter.convert(o);
          } catch (ConverterException e) {
            ctx.warn("Conversion error", e);
            return null;
          }
        }
      }
    }

    return arg;
  }