Mapping enum to String

2,513 views
Skip to first unread message

Paul Strugnell

unread,
May 8, 2015, 5:45:17 AM5/8/15
to mapstru...@googlegroups.com
Hi all

I have noticed that my MapStruct-generated mapper classes use toString() to convert an enum value to a String object, but this is unsafe as somebody may later override toString() on the enum class, thus causing the mapping to change.

I want to the mapper to use name(), since it is guaranteed to return the enum value exactly as declared.

Is there any way to use name() instead of toString()?

Thanks!

Gunnar Morling

unread,
May 8, 2015, 6:01:07 AM5/8/15
to Paul Strugnell, mapstru...@googlegroups.com
Hi,

There is no way to do this, but I agree that this would be better.

I have filed https://github.com/mapstruct/mapstruct/issues/540 for this and assigned it to the upcoming CR1 release. Would you be interested in contributing a fix? Should probably just be a small change in https://github.com/mapstruct/mapstruct/blob/master/processor/src/main/java/org/mapstruct/ap/conversion/EnumStringConversion.java.

Thanks,

--Gunnar


--
You received this message because you are subscribed to the Google Groups "mapstruct-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mapstruct-use...@googlegroups.com.
To post to this group, send email to mapstru...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Paul Strugnell

unread,
May 8, 2015, 6:12:04 AM5/8/15
to mapstru...@googlegroups.com
I'm tempted to simply change toString() to name(), but I think this would only be appropriate if there are no valid use cases for toString(). I wouldn't want to break anyone's code.

Would it be possible/worthwhile to make it configurable (e.g. using an annotation on the mapper) so that developers can choose the implementation they want?

Paul Strugnell

unread,
May 8, 2015, 6:33:56 AM5/8/15
to mapstru...@googlegroups.com
I have created a pull request for changing toString() to name() - https://github.com/mapstruct/mapstruct/pull/541

Gunnar Morling

unread,
May 8, 2015, 7:21:43 AM5/8/15
to mapstru...@googlegroups.com, paulst...@powa.com
IMO it's safe to do the proposed change.

It won't affect anybody not overriding toString() (which I think is the vast majority of cases). For those who do override it, the current approach is not optimal anyways, because it makes the generated mapping asymmetric: enum -> string is mapped via toString(), whereas string -> enum is mapped via valueOf() which expects the enum member name.

I don't think it's worth the have an option for this. Those who really need to customize this, can do so via their own mapping method on a hand-written mapper and plugging this in.

Thanks for your PR. I will merge it ASAP. To be extra-safe, we can add an entry to the migration notes.

Cheers,

--Gunnar
Reply all
Reply to author
Forward
0 new messages