Java / MapStruct Java Interview questions part 2
How do you map an enum to a different enum with mismatched constants?
By default MapStruct maps enum constants that share the exact same name automatically. When names differ between the source and target enums, @ValueMapping lets you specify the correspondence explicitly.
@Mapper public interface StatusMapper { @ValueMapping(source = "ACTIVE", target = "ENABLED") @ValueMapping(source = "INACTIVE", target = "DISABLED") TargetStatus toTargetStatus(SourceStatus source); }
You can also handle values with no equivalent using special targets like NULL (map to null) or ANY_UNMAPPED combined with a designated fallback constant, and MapStruct will warn at compile time if a source constant has no mapping rule and no equally-named match, so an unhandled enum value doesn't silently fail at runtime.
More Related questions...