[英]MapStruct: error occur when using Target field type as Object
When I tried for MapStruct to convert type to Object, it didn't work well.当我尝试让 MapStruct 将类型转换为 Object 时,效果不佳。
Target Class目标班级
public static class Filterable implements Name,Disassemble,Note{
String name;
String disassemble;
Object note; // <-- Object type
... getter setter
}
Mapping abstract class映射抽象类
@Mappings({
@Mapping(source = "s",target = "name"),
@Mapping(source = "s",target = "note"), // <--
@Mapping(source = "s",target = "disassemble", qualifiedByName = "toDisassemble")
})
public abstract UiDto.Option.Filterable toUiFilterableOption(String s);
Result when I compile我编译时的结果
@Override
public Filterable toUiFilterableOption(String s) {
if ( s == null ) {
return null;
}
Filterable filterable = new Filterable();
filterable.setName( s );
filterable.setNote( toUiFilterableOption( s ) ); // <-- hear is problem
filterable.setDisassemble( Converter.toDisassemble( s ) );
return filterable;
}
How could I solve this problem?我怎么能解决这个问题?
MapStruct tries to find a method that maps from the source class to the target class: Object map(String source)
. MapStruct 试图找到一种从源类映射到目标类的方法:
Object map(String source)
。
As far as the target class is Object
, the method annotated with @Mapping
itself has suitable method signature: Filterable toUiFilterableOption(String s)
.只要目标类是
Object
,用@Mapping
注释的方法本身就有合适的方法签名: Filterable toUiFilterableOption(String s)
。 Because Filterable
just like any other class in Java is an Object
.因为
Filterable
就像 Java 中的任何其他类一样是一个Object
。 And the method argument also is a String
.并且方法参数也是一个
String
。
To solve this issue use qualifiedByName
in @Mapping
and add a mapping method annotated with @Named
:要解决此问题,请在
@Mapping
使用qualifiedByName
并添加用@Named
注释的映射方法:
@Mapper
public abstract class TestMapper {
public static final TestMapper TEST_MAPPER = Mappers.getMapper(TestMapper.class);
@Mapping(source = "s", target = "name")
@Mapping(source = "s", target = "note", qualifiedByName = "toNote")
@Mapping(source = "s", target = "disassemble", qualifiedByName = "toDisassemble")
public abstract Filterable toUiFilterableOption(String s);
@Named("toNote")
protected Object toNote(String s) {
return s.toUpperCase(); //just as an example
}
//...
}
The generated code looks like this:生成的代码如下所示:
public class TestMapperImpl extends TestMapper {
@Override
public Filterable toUiFilterableOption(String s) {
if (s == null) {
return null;
}
Filterable filterable = new Filterable();
filterable.setName(s);
filterable.setNote(toNote(s));
filterable.setDisassemble(toDisassemble(s));
return filterable;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.