Backend Development 4 min read

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.

JD Cloud Developers
JD Cloud Developers
JD Cloud Developers
Why BeanUtils.copyProperties Causes ClassCastException and How to Fix It

Background

During an agile team project, a unit test triggered a

java.lang.ClassCastException

because a service interface returned a

java.util.HashMap

that could not be cast to the expected

BatchInfo

class.

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&lt;CargoInfo&gt; 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.copyProperties

performs 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

.

ClassCastException flow diagram
ClassCastException flow diagram

An additional diagram visualizes the shallow‑copy problem.

Shallow copy illustration
Shallow copy illustration

Solution and Reflections

Removing

BeanUtils.copyProperties

and 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.

Recommendation to avoid BeanUtils.copyProperties
Recommendation to avoid BeanUtils.copyProperties
DebuggingJavaBeanUtilsMapStructClassCastExceptioncopyProperties
JD Cloud Developers
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.