地图枚举到字符串值

发布于 2025-02-04 09:48:12 字数 683 浏览 3 评论 0原文

我正在使用Mapstruct的最新版本。我正在尝试将相应字符串值的值映射到实际enum值。

例如,这是我的enum

@Getter
@RequiredArgsConstructor
@Accessors(fluent = true)
public enum Type {
  T1("SomeValue"),
  T2("AnotherValue");

  private final String label;
}

我有一个接收数据的字段/成员java type(forefertypeenum)中的字符串值:somevalueentersValue。然后,我有一个“受控”类型(myType),并且我想在此中使用实际的枚举常数(t1t2) ,基于发送的字符串值。

我正在寻找一种使用mapsstruct来执行此操作的方法,因为该应用程序当前将其用于所有映射目的,但是到目前为止,我还找不到实现此目的的方法。

I'm using a recent version of MapStruct. I'm trying to map the values of the corresponding string values to the actual enum value.

For instance, this is my enum:

@Getter
@RequiredArgsConstructor
@Accessors(fluent = true)
public enum Type {
  T1("SomeValue"),
  T2("AnotherValue");

  private final String label;
}

I have a Java type (ForeignType) with a field/member that receives the data (one of the string values in the enum): SomeValue or AnotherValue. Then I have a "controlled" type (MyType) and I would like to use in this one the actual enumeration constant (T1 or T2), based on string value sent.

I'm looking for a way to use MapStruct to do this, because the application currently uses it for all mapping purposes, but so far I can't find a way to achieve this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵性 2025-02-11 09:48:12

映射的概念@valuemapping,可用于将字符串映射到enum中。

例如,

@Mapper
public interface TypeMapper {


    @ValueMapping(target = "T1", source = "SomeValue")
    @ValueMapping(target = "T2", source = "AnotherValue")
    Type map(String type);


}

执行上述映射将为您实现一种方法。但是,另一种方法是使用自定义方法进行映射:

例如

public interface TypeMapper {

    default Type map(String type) {
        if (type == null) {
            return null;
        }

        for(Type t: Type.values()) {
            if (type.equals(t.label()) {
                return t;
            }
        }

        throw new IllegalArgumentException("Cannot map label " + type + " to type");
    }

}

MapStruct has the concept of @ValueMapping that can be used to map a String into an Enum.

e.g.

@Mapper
public interface TypeMapper {


    @ValueMapping(target = "T1", source = "SomeValue")
    @ValueMapping(target = "T2", source = "AnotherValue")
    Type map(String type);


}

Doing the above MapStruct will implement a method for you. However, an alternative approach would be to use a custom method to do the mapping:

e.g.

public interface TypeMapper {

    default Type map(String type) {
        if (type == null) {
            return null;
        }

        for(Type t: Type.values()) {
            if (type.equals(t.label()) {
                return t;
            }
        }

        throw new IllegalArgumentException("Cannot map label " + type + " to type");
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文