Dozer 字符串到枚举映射

发布于 2024-12-18 00:31:41 字数 1388 浏览 3 评论 0原文

我有这样的枚举:

public enum PartnershipIndicator {
    VENDOR("VENDOR"), COPARTNER("COPARTNER"), BUYER("BUYER");

    String code;

    private PartnershipIndicator(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public static PartnershipIndicator valueOfCode(String code) {
        for (PartnershipIndicator status : values()) {
            if (status.getCode().equals(code)) {
                return status;
            }
        }
        throw new IllegalArgumentException(
            "Partnership status cannot be resolved for code " + code);
    }

    @Override
    public String toString() {
        return code;
    }
}

我需要将其转换为字符串,反之亦然。 现在,它是由自定义转换器完成的。但我想通过推土机映射来完成(如果可能的话)。如果我不向推土机配置写入任何映射,则会出现

org.dozer.MappingException: java.lang.NoSuchMethodException: by.dev.madhead.demo.test_java.model.PartnershipIndicator.<init>()

异常。我无法将默认公共构造函数添加到枚举中,因为这是不可能的。因此,我用内部代码和 valueOfCode() / toString() 编写了一个技巧。它不起作用。然后,我将其映射到推土机配置中:

<mapping>
    <class-a>java.lang.String</class-a>
    <class-b create-method="valueOfCode">by.dev.madhead.demo.test_java.model.PartnershipIndicator</class-b>
</mapping>

它不起作用。我尝试了 valueOfCode(),单向映射。什么都不起作用。枚举到字符串的转换也不起作用,我得到空字符串。 有什么想法吗?

I have such enum:

public enum PartnershipIndicator {
    VENDOR("VENDOR"), COPARTNER("COPARTNER"), BUYER("BUYER");

    String code;

    private PartnershipIndicator(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public static PartnershipIndicator valueOfCode(String code) {
        for (PartnershipIndicator status : values()) {
            if (status.getCode().equals(code)) {
                return status;
            }
        }
        throw new IllegalArgumentException(
            "Partnership status cannot be resolved for code " + code);
    }

    @Override
    public String toString() {
        return code;
    }
}

I need to convert it to String and vice versa. Now, it is done by custom converter. But i want to do it via dozer mappings (if it is possible). If i do not write any mappings to the dozer confing, i get

org.dozer.MappingException: java.lang.NoSuchMethodException: by.dev.madhead.demo.test_java.model.PartnershipIndicator.<init>()

exception. I cannot add default public constructor to enum, as it is not possible. So, i wrote a trick with internal code and valueOfCode() / toString(). It does not work. Then, i've mapped it in dozer config:

<mapping>
    <class-a>java.lang.String</class-a>
    <class-b create-method="valueOfCode">by.dev.madhead.demo.test_java.model.PartnershipIndicator</class-b>
</mapping>

It does not work. I tried valueOfCode(), one-way mappings. Nothing works. Enum to String conversion does not work too, i get empty Strings.
Any ideas?

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

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

发布评论

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

评论(2

甜心 2024-12-25 00:31:41

不确定这是否仍然是一个问题,但也许对任何搜索的人都有帮助。但这里是对此的实现解决方案:

@Override
public Object convert(Object destination, Object source, Class<?> destinationClass,    Class<?> sourceClass) {
    if(source == null)
        return null;
    if(destinationClass != null){
        if(destinationClass.getSimpleName().equalsIgnoreCase("String")){
            return this.getString(source);
        }else if( destinationClass.isEnum()){

            return this.getEnum(destinationClass, source);

        }else{
            throw new MappingException(new StrBuilder("Converter ").append(this.getClass().getSimpleName())
                       .append(" was used incorrectly. Arguments were: ")
                       .append(destinationClass.getClass().getName())
                       .append(" and ")
                       .append(source).toString());
        }
    }
    return null;
}

private Object getString(Object object){
    String value = object.toString();
    return value;
}
private Object getEnum(Class<?> destinationClass, Object source){
    Object enumeration = null;

    Method [] ms = destinationClass.getMethods();
    for(Method m : ms){
        if(m.getName().equalsIgnoreCase("valueOf")){
            try {
                enumeration = m.invoke( destinationClass.getClass(), (String)source);
            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return enumeration;
        }
    }
    return null;
}

构建异常消息时的 StrBuilder 类来自 apaches common-lang 库。但除此之外,还可以通过简单的反思来解决这个问题。只需添加到实现 CustomConverter 的类,然后在您的 dozer 映射 xml 文件中添加以下配置:

<configuration>
    <custom-converters>
        <converter type="com.yourcompany.manager.utils.dozer.converters.EnumStringBiDirectionalDozerConverter">
            <class-a>java.lang.Enum</class-a>
            <class-b>java.lang.String</class-b>
        </converter>
    </custom-converters>
</configuration>

请注意,您只能在所有映射文件(如果有多个)之间列出一次配置,否则 dozer 会抱怨。为了简单起见,我通常所做的是将自定义转换器配置放在一个文件中。希望这有帮助!

Not sure if this is still an issue, but maybe help for anyone searching. But here is implemented solution to this:

@Override
public Object convert(Object destination, Object source, Class<?> destinationClass,    Class<?> sourceClass) {
    if(source == null)
        return null;
    if(destinationClass != null){
        if(destinationClass.getSimpleName().equalsIgnoreCase("String")){
            return this.getString(source);
        }else if( destinationClass.isEnum()){

            return this.getEnum(destinationClass, source);

        }else{
            throw new MappingException(new StrBuilder("Converter ").append(this.getClass().getSimpleName())
                       .append(" was used incorrectly. Arguments were: ")
                       .append(destinationClass.getClass().getName())
                       .append(" and ")
                       .append(source).toString());
        }
    }
    return null;
}

private Object getString(Object object){
    String value = object.toString();
    return value;
}
private Object getEnum(Class<?> destinationClass, Object source){
    Object enumeration = null;

    Method [] ms = destinationClass.getMethods();
    for(Method m : ms){
        if(m.getName().equalsIgnoreCase("valueOf")){
            try {
                enumeration = m.invoke( destinationClass.getClass(), (String)source);
            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return enumeration;
        }
    }
    return null;
}

The StrBuilder class when building the exception message is from the apaches common-lang libs. But other than that a simple reflection to solve this issue. Just add to a class that implements CustomConverter and then in your dozer mapping xml file add the following configuration:

<configuration>
    <custom-converters>
        <converter type="com.yourcompany.manager.utils.dozer.converters.EnumStringBiDirectionalDozerConverter">
            <class-a>java.lang.Enum</class-a>
            <class-b>java.lang.String</class-b>
        </converter>
    </custom-converters>
</configuration>

Note that you can only list a configuration once between all of your mapping files (if you have multiple) otherwise dozer will complain. What I typically do is place my custom converter configurations in one file for simplicity. Hope this helps!

怕倦 2024-12-25 00:31:41

Dozer 中没有默认的字符串映射枚举。请参阅 Dozer 文档中的数据类型转换。因此,您有两个选择:

  • 您可以编写一个使用泛型来处理任何枚举的自定义转换器。
  • 或者,您可以向 Dozer 提交补丁,以将 enum<->String 映射添加到默认映射。

There isn't a default enum to String mapping in Dozer. See Data type conversion from Dozer docs. So you have two options:

  • You can write a custom converter that uses generics to handle any enum.
  • Or, you could submit a patch to Dozer to add enum<->String mapping to the default mappings.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文