gpt4 book ai didi

java - 自定义推土机映射

转载 作者:行者123 更新时间:2023-11-29 06:14:04 25 4
gpt4 key购买 nike

我正在尝试使用 Dozer 来转换

class Source {
private List<Foo> foos = new ArrayList<Foo>();

public List<Foo> getFoos() {
return foos;
}

public void setFoos(List<Foo> foos) {
this.foos = foos;
}
}

一个实例:

class Target {
private List<Foo> foos = new ArrayList<Foo>();

public List<Foo> getFoos() {
return foos;
}
}

在 Java 代码中,我会像这样执行转换

Source s = new Source();
Target t = new Target();
t.getFoos().addAll(s.getFoos());

默认情况下,Dozer 不执行此转换,因为 Target 没有 foos 属性(只是一个 getter)。

实际上,我有很多这样的属性需要映射。一种选择是告诉 Dozer map the private fields directly ,但这并不完全令人满意,因为:

  • 我需要在 Dozer XML 配置中指定要以这种方式映射的每个字段
  • 访问私有(private)字段是不好的

有没有更好的办法?

最佳答案

除了 is-accessible 标志之外,没有简单的方法来解决这个问题。但是您可以定义一个使用 getter 的自定义转换器:

t.getFoos().addAll(s.getFoos());

这将是非常繁重的工作。您需要在 SourceTarget 之间定义一个自定义转换器(请参阅 http://dozer.sourceforge.net/documentation/customconverter.html ),该转换器使用 getter 而不是 setter:

public class TestCustomConverter implements CustomConverter {

public Object convert(Object destination, Object source, Class destClass, Class sourceClass) {
if (source == null) {
return null;
}
if (source instanceof Source) {
Target dest = null;
// check to see if the object already exists
if (destination == null) {
dest = new Target();
} else {
dest = (Target) destination;
}
dest.getFoos().addAll(((Source)source).getFoos());
return dest;
} else if (source instanceof Target) {
Source dest = null;
// check to see if the object already exists
if (destination == null) {
dest = new Source();
} else {
dest = (Source) destination;
}
dest.setFoos(((Target)source).getFoos());
return dest;
} else {
throw new MappingException("Converter TestCustomConverter used incorrectly. Arguments passed in were:"
+ destination + " and " + source);
}
}

我想,祝你好运

关于java - 自定义推土机映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5745101/

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