Java 推土机自定义转换器 - 将整个对象作为字段“A”传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20494054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:19:58  来源:igfitidea点击:

Dozer custom converter - passing the whole object as field 'A'

javaxml-serializationdozer

提问by lance-java

I'd like to map a CustomConverter in dozer but I'd like to pass the whole current object as the source. All of the examples in the dozer CustomConverter documentation pass a field of the input object as the source and not the whole object.

我想在推土机中映射一个 CustomConverter,但我想将整个当前对象作为源传递。dozer CustomConverter 文档中的所有示例都将输入对象的字段作为源而不是整个对象传递。

I'd like to do something like this:

我想做这样的事情:

<mapping>
   <class-a>foo.bar.InputObject</class-a>
   <class-b>foo.bar.OutputObject</class-b>    
   <field custom-converter="foo.bar.MyConverter">
      <a>this</a> <!-- how do I access the whole value and not just a field? -->
      <b>custom</b>
   </field>
   <field>
      <a>anotherField</a>
      <b>anotherField</b>
   </field>
</mapping>

And

public class MyConverter extends DozerConverter<InputObject, String> {
    ...
    public String convertTo(InputObject input, String custom) {
       // do some transformation
    }
}

CustomConverter docs here: http://dozer.sourceforge.net/documentation/customconverter.html

CustomConverter 文档在这里:http: //dozer.sourceforge.net/documentation/customconverter.html

回答by Prasann

Try implementing the CustomConverter instead of DozerConverter and try passing it as:

尝试实现 CustomConverter 而不是 DozerConverter 并尝试将其传递为:

<field custom-converter="my.custom.converter">
    <a>this</a>
    <b>myfield</b>
</field>

回答by fl0w

If you use the field mapping you want to identify the attribute by using "key":

如果您使用字段映射,您希望使用“key”来标识属性:

<field custom-converter="de.xyz.custom.MyConverter">
    <a key="variablename">this</a>
    <b>targetvariablename</b>
</field>

You can then proceed to implement the converter. You will be given the Object containing the field "variablename" as source. If for example you do not have a setter for a list value (like I had for whatever reason...) you are now able to manipulate the source object the way you need to.

然后,您可以继续实施转换器。您将获得包含字段“变量名”的对象作为源。例如,如果您没有列表值的设置器(就像我出于任何原因那样......),您现在可以按照您需要的方式操作源对象。