Debugging ClassCastException Caused by BeanUtils.copyProperties Shallow Copy in Java Services
The article details a real‑world debugging case where a Java service threw a ClassCastException due to BeanUtils.copyProperties performing a shallow copy, explains the investigation steps, shows the problematic code, and presents a manual‑assignment solution along with reflections on safer alternatives.
Background : During an agile team project a delayed test revealed a runtime java.lang.ClassCastException: java.util.HashMap cannot be cast to cn.xxx.xxx.xxx.xxx.BatchInfo when invoking a service without any interface changes.
Investigation Process :
Checked the request payload format with the service provider; the call succeeded, indicating the payload was correct.
Reviewed serialization methods and recent code changes with teammates.
Wrote a unit test to confirm the server received the expected payload.
Inspected the code and identified the use of BeanUtils.copyProperties(item, cargoInfo) as suspicious.
private List
convertToCargoInfo(OutboundEventCallbackRequest outboundEventCallbackRequest) {
return outboundEventCallbackRequest.getCargos().stream().map(item -> {
CargoInfo cargoInfo = new CargoInfo();
BeanUtils.copyProperties(item, cargoInfo);
return cargoInfo;
}).collect(Collectors.toList());
}Root Cause : BeanUtils.copyProperties performs a shallow copy, copying only reference fields via setters. When the target object contains nested structures, the shallow copy leaves a Map representation, causing the deserialization layer (JSF) to produce a HashMap instead of the expected BatchInfo class, leading to the ClassCastException .
Solution : Removed the shallow‑copy utility and manually assigned the required fields, which eliminated the exception. For projects with many such conversions, using a compile‑time mapper like MapStruct is recommended.
Reflections :
Prefer simple, stable code over complex utilities (as echoed by a senior mentor).
Consider MapStruct for repetitive bean mapping tasks.
Use BeanUtils.copyProperties cautiously; understand its shallow‑copy semantics.
Additional resources and related articles are linked at the end of the original post.
JD Tech
Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.