Skip to content
Why BeanUtils.copyProperties Causes ClassCastException and How to Fix It

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

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:

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());
}

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
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

debuggingJavaBeanUtilsMapStructClassCastExceptionCopyProperties
Reader feedback

How this landed with the community

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.