chinabugotech/hutool · error · ConvertException

Can not cast value to [{}]

Error message

Can not cast value to [{}]

What it means

CastConverter.convertInternal is a last-resort force-cast. AbstractConverter already attempted targetType.cast(value) before reaching convertInternal, so arriving here means the value is not assignable to targetType; it throws ConvertException naming the target type.

Source

Thrown at hutool-core/src/main/java/cn/hutool/core/convert/impl/CastConverter.java:21

import cn.hutool.core.convert.AbstractConverter;
import cn.hutool.core.convert.ConvertException;

/**
 * 强转转换器
 *
 * @author Looly
 * @param <T> 强制转换到的类型
 * @since 4.0.2
 */
public class CastConverter<T> extends AbstractConverter<T> {
	private static final long serialVersionUID = 1L;

	private Class<T> targetType;

	@Override
	protected T convertInternal(Object value) {
		// 由于在AbstractConverter中已经有类型判断并强制转换,因此当在上一步强制转换失败时直接抛出异常
		throw new ConvertException("Can not cast value to [{}]", this.targetType);
	}

	@Override
	public Class<T> getTargetType() {
		return this.targetType;
	}
}

View on GitHub (pinned to 8870454b2a)

Solutions

  1. Pre-check value instanceof targetType before attempting a cast conversion.
  2. Use the proper typed converter (NumberConverter, etc.) instead of CastConverter for cross-type conversion.
  3. Pass a defaultValue so AbstractConverter returns it rather than invoking convertInternal.

Example fix

// before
Integer i = castConverter.convert("abc", null);

// after - guard then convert properly
Integer i = (value instanceof Integer) ? (Integer) value : NumberConverter.convert(value);
Defensive patterns

Strategy: type-guard

Validate before calling

if (!castConverter.getTargetType().isInstance(value)) {
    // use a real converter instead of a cast
    return Convert.convert(value, castConverter.getTargetType());
}

Type guard

castConverter.getTargetType() != null && castConverter.getTargetType().isInstance(value)

Try / catch

try {
    return castConverter.convert(value, null);
} catch (ConvertException e) {
    if (e.getMessage().startsWith("Can not cast value to")) { /* fall back to Convert */ }
    else throw e;
}

Prevention

When it happens

Trigger: A CastConverter (or registered cast path) is invoked on a value whose runtime class is not assignable to the configured targetType.

Common situations: Custom conversion chains that fall back to CastConverter; converting between unrelated class hierarchies (e.g. String to Integer via cast).

Related errors


AI-assisted analysis of chinabugotech/hutool@8870454b2a (2026-08-14). Data as JSON: /api/errors/cc22356b5a6a48ba. Report an issue: GitHub.