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
- Pre-check value instanceof targetType before attempting a cast conversion.
- Use the proper typed converter (NumberConverter, etc.) instead of CastConverter for cross-type conversion.
- 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
- Avoid CastConverter for cross-type conversion; use the typed converter for the source.
- Pre-check instanceof before attempting a cast-based conversion.
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
- Default value [{}]({}) is not the instance of [{}]
- Unsupported source type: {}
- Unsupported to map from [{}] of type: {}
- Unsupported {} to Map.
- Unsupported toMap value type: {}
AI-assisted analysis of chinabugotech/hutool@8870454b2a (2026-08-14).
Data as JSON: /api/errors/cc22356b5a6a48ba.
Report an issue: GitHub.