Skip to content

Add compiler flag to disable automatic String-To-Enum conversions #4004

@tram98

Description

@tram98

Use case

There currently seems to be no way of preventing the automatic String-To-Enum conversion generated by the annotation processor.

For my use case, this is unwanted behaviour that hides the loss of type safety in this mapping. I'd like to be able to disable this feature and have the compiler emit an error instead.

Example:

In the following example, I map a class of type Fruit to another class of type FruitDefinition.

The Fruit class declares a property fruitType of type String.
The FruitDefinition class declares fruitType as an Enum FruitType.

When mapping from Fruit to FruitDefinition, it is possible that the input string does not match any of the declared enum values.

I would like to prevent this at compile time rather than having it cause an IllegalArgumentException at runtime.

class Fruit {

    String fruitType;
}

enum FruitType {
   APPLE, PEACH, CHERRY
}

class FruitDefinition {
    FruitType fruitType;
}

@Mapper
interface FruitMapper {

    @Mapping(target = "fruitType", source = "fruitType")
    FruitDefinition fromFruit(Fruit fruit);
}

Above example compiles to something like this:

// ...
if ( fruit.fruitType != null ) {
    fruitDefinition.setFruitType(Enum.valueOf(FruitType.class, fruit.fruitType));
}
// ...

I'd suggest to implement a sort of StringToEnumMappingStrategy, supporting the following options:

  • ALLOW_MAPPING (default): implement behaviour as it is now
  • DISALLOW_MAPPING: prevent mapping at compile time and return an appropriate error message.

This strategy should be specifiable at both @Mapper level and compiler-options level.

If you approve of this proposal, I'd be open to implement it myself.

Generated Code

No response

Possible workarounds

MapStruct Version

MapStruct 1.6.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions