gpt4 book ai didi

java - 推土机 5.3.2。以编程方式设置自定义转换器?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:30:51 26 4
gpt4 key购买 nike

如何以编程方式为推土机设置自定义转换器?以下代码不起作用:

自定义转换器实现:

class ConverterImpl extends DozerConverter<A, B> {

ConverterImpl() {
super(A.class, B.class);
}

@Override
public B convertTo(A source, B destination) {
return destination;
}

@Override
public A convertFrom(B source, A destination) {
return destination;
}
}

测试代码:

DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomConverters(Collections.<CustomConverter>singletonList(new ConverterImpl()));
A a = new A();
B b = mapper.map(a, A.class);

运行上面的代码后,自定义转换器不会被调用。怎么了?

最佳答案

看起来您必须实际添加一个特定的映射,不幸的是您只能使用编程 API 指定字段级转换器,而不是类级转换器。因此,如果将 A 和 B 类包装在容器类中,则可以为 A 和 B 字段指定一个映射。

例如,以下冗长的代码按预期工作:

public class DozerMap {

public static class ContainerA {
private A a;
public A getA() { return a; }
public void setA(A a) { this.a = a; }
}

public static class ContainerB {
private B b;
public B getB() { return b; }
public void setB(B b) { this.b = b; }
}

private static class A { };

private static class B { };

static class ConverterImpl extends DozerConverter<A, B> {

ConverterImpl() {
super(A.class, B.class);
}

@Override
public B convertTo(A source, B destination) {
Logger.getAnonymousLogger().info("Invoked");
return destination;
}

@Override
public A convertFrom(B source, A destination) {
Logger.getAnonymousLogger().info("Invoked");
return destination;
}
}

public static void main(String[] args) {

DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomConverters(Collections.<CustomConverter> singletonList(new ConverterImpl()));
BeanMappingBuilder foo = new BeanMappingBuilder() {

@Override
protected void configure() {
mapping(ContainerA.class, ContainerB.class).fields("a", "b", FieldsMappingOptions.customConverter(ConverterImpl.class));
}
};
mapper.setMappings(Collections.singletonList(foo));
ContainerA containerA = new ContainerA();
containerA.a = new A();
ContainerB containerB = mapper.map(containerA, ContainerB.class);
}
}

关于java - 推土机 5.3.2。以编程方式设置自定义转换器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10579368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com