Core Java

Mapping Enums and Strings with MapStruct

MapStruct is a Java annotation processor that streamlines the implementation of mappings between Java beans, including complex scenarios such as converting Enums to Strings and vice versa. This article explores various enum to string mapping techniques using MapStruct.

1. Mapping an Enum to a String

Let’s say we have an Enum and want to map it to a String representation for various purposes like JSON serialization.

1.1 Example

Define an Enum:

Status.java

public enum Status {
    ACTIVE, INACTIVE, PENDING
}

1.2 MapStruct Mapper

We want to map the above enum to a string. Let’s define the Mapper interface:

StatusMapper.java

@Mapper
public interface StatusMapper {
    
    StatusMapper INSTANCE = Mappers.getMapper(StatusMapper.class);

    String toString(Status status);
}

Usage:

EnumToString.java

public class EnumToString {

    public static void main(String[] args) {

        Status status = Status.ACTIVE;
        // Singleton instance
        StatusMapper mapper = StatusMapper.INSTANCE;

        // Handle a valid enum value
        String statusString = mapper.toString(status);
        System.out.println(statusString);
    }
}

Here, mapper.toString(Status status) will return the string representation of the status enum value.

Output:

ACTIVE

2. Mapping a String to an Enum

MapStruct can also convert strings back to enums. It attempts to match the string value with the corresponding enum constant name (case-sensitive). In this example, we convert a String to its corresponding Enum value, often required for deserializing JSON or handling user inputs.

2.1 MapStruct Mapper

StatusMapper.java

@Mapper
public interface StatusMapper {
    StatusMapper INSTANCE = Mappers.getMapper(StatusMapper.class);

    Status toEnum(String status);
}

Usage:

public class StringToEnum {

    public static void main(String[] args) {

        String statusString = "INACTIVE";
        Status status = StatusMapper.INSTANCE.toEnum(statusString);
        System.out.println(status); 
    }
}

In this example, StatusMapper.toEnum("INACTIVE") will return the Status.INACTIVE enum value.

Note: If the string doesn’t match an existing enum constant, MapStruct throws an exception.

3. Mapping an Enum to a Custom String

Sometimes, we might want to map an enum to a custom string representation that differs from the toString() method. MapStruct’s @ValueMapping annotation allows for such customization.

3.1 MapStruct Mapper

StatusMapper.java

@Mapper
public interface StatusMapper {

    StatusMapper INSTANCE = Mappers.getMapper(StatusMapper.class);

    @ValueMapping(source = "PENDING", target = "Pending Approval")
    @ValueMapping(source = "ACTIVE", target = "Active Status")
    @ValueMapping(source = "INACTIVE", target = "Inactive Status")
    String toString(Status status);
}

Here, StatusMapper.toString(Status status) will map each enum value to a custom string representation defined in the @ValueMapping annotations.

Usage:

EnumToCustomString.java

public class EnumToCustomString {

    public static void main(String[] args) {
        
        Status status = Status.ACTIVE;
        // Singleton instance
        StatusMapper mapper = StatusMapper.INSTANCE;
        
        String statusString = mapper.toString(status);
        //String statusString = StatusMapper.INSTANCE.toString(status);
        System.out.println(statusString); 
    }
}

Output:

Active Status

4. Mapping a Custom String to an Enum

Similar to mapping Enum to a custom String, we can convert from a custom String back to Enum.

4.1 MapStruct Mapper with Reverse Mapping

MapStruct can leverage @InheritInverseConfiguration to define reverse mappings, ensuring that the mapping from custom strings to Enums is the inverse of the mapping from Enums to custom strings.

StatusMapper.java

@Mapper
public interface StatusMapper {

    StatusMapper INSTANCE = Mappers.getMapper(StatusMapper.class);
    
    @InheritInverseConfiguration(name = "toString")
    Status toStatus(String statusString);
}

Usage:

public class EnumToCustomString {

    public static void main(String[] args) {
        
        String customString = "Pending Approval";
        Status status = StatusMapper.INSTANCE.toStatus(customString);
        System.out.println(status); // Output: PENDING

    }
}

In this example, the toStatus(customString) method uses @InheritInverseConfiguration to reverse the logic defined in toString(status).

5. Conclusion

In this article, we demonstrated how to map an enum to a string using MapStruct, covering various scenarios:

  • Mapping an enum to a string
  • Mapping a string to an enum
  • Mapping an enum to a custom string
  • Mapping a custom string to an enum

By leveraging the default toString() method and @ValueMapping annotations, we can achieve various mapping scenarios tailored to our specific needs.

6. Download the Source Code

This article covered the use of MapStruct for mapping an Enum to a String and vice versa.

Download
You can download the full source code of this example here: Mapstruct Enum String

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button