Why BeanUtils.copyProperties Causes ClassCastException and How to Fix It
A Java backend debugging story explains how using BeanUtils.copyProperties led to a ClassCastException when a HashMap was cast to a custom class, details the investigation steps, shows the problematic code, and presents a manual assignment solution plus recommendations for safer mapping tools.
Background
During an agile team project, a unit test triggered a
java.lang.ClassCastExceptionbecause a service interface returned a
java.util.HashMapthat could not be cast to the expected
BatchInfoclass.
Investigation Process
The team first suspected the request payload format and used testing tools and local debugging to verify the payload, which succeeded. Next they examined the serialization method and recent code changes, focusing on a suspicious line:
<code>private List<CargoInfo> convertToCargoInfo(OutboundEventCallbackRequest outboundEventCallbackRequest) {
return outboundEventCallbackRequest.getCargos().stream().map(item -> {
CargoInfo cargoInfo = new CargoInfo();
BeanUtils.copyProperties(item, cargoInfo);
return cargoInfo;
}).collect(Collectors.toList());
}</code>The root cause was that
BeanUtils.copyPropertiesperforms a shallow copy, copying only reference fields. During deserialization the framework could not locate the target class and converted the object to a
Map, leading to the
ClassCastException.
An additional diagram visualizes the shallow‑copy problem.
Solution and Reflections
Removing
BeanUtils.copyPropertiesand assigning fields manually resolved the issue. The team reflected that shallow‑copy utilities can be risky and recommended using a dedicated mapper such as MapStruct for complex conversions.
JD Cloud Developers
JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.
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.