Skip to content

BeanUtils.copyProperties() does not correctly copy enum fields #33361

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
takkiraz opened this issue Aug 9, 2024 · 2 comments
Closed

BeanUtils.copyProperties() does not correctly copy enum fields #33361

takkiraz opened this issue Aug 9, 2024 · 2 comments
Labels
status: invalid An issue that we don't feel is valid

Comments

@takkiraz
Copy link

takkiraz commented Aug 9, 2024

Description

I encountered an issue with BeanUtils.copyProperties() in Spring Framework where it does not correctly copy enum fields in a Kotlin data class. Below is a minimal reproducible example that demonstrates the problem.

@SpringBootTest
class ApplicationTests {

    @Test
    fun `should copy enum fields with BeanUtils`() {
        val source= User(1, "John", UserRole.ADMIN)
        val target = User(0, "")
        BeanUtils.copyProperties(source, target)
        assert(target.role == source.role)  // This fails
    }
}

data class User(
    val id: Long,
    val name: String,
    val role: UserRole = UserRole.USER
)

enum class UserRole {
    USER, ADMIN, CUSTOMER
}

Expected Behaviour

The role field in target should be UserRole.ADMIN after calling BeanUtils.copyProperties(source, target).

Actual Behavior:

The role field in target remains UserRole.USER, indicating that the enum field was not copied correctly.

Environment:

Spring Framework version: 6.1.1

@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Aug 9, 2024
@jhoeller
Copy link
Contributor

jhoeller commented Aug 9, 2024

You need to declare those data class fields as var instead of val, otherwise Kotlin does not generate Java setter methods at all. In your case, it's not just the enum field but rather none of those fields getting copied.

@jhoeller jhoeller closed this as not planned Won't fix, can't repro, duplicate, stale Aug 9, 2024
@jhoeller jhoeller added status: invalid An issue that we don't feel is valid and removed status: waiting-for-triage An issue we've not yet triaged or decided on labels Aug 9, 2024
@takkiraz
Copy link
Author

takkiraz commented Aug 9, 2024

Thank you for the clarification! I actually noticed the mistake right after creating the ticket—sorry for the unnecessary noise. Lesson learned—var it is!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: invalid An issue that we don't feel is valid
Projects
None yet
Development

No branches or pull requests

3 participants