我有以下结构
Public void Student(){
private string name;
private int age;
}
Public void Class(){
private string roomNo;
private Student student; //Student Object
}
Public void School(){
private string roomNo;
private String student; //String student
}
我正在尝试使用映射结构来映射这些
@Mapping(source = "java(student.toString())", target = "student")
School mapClassToSchool(@NonNull Class class);
我得到以下错误
error: No property named "java(student.toString())" exists in source parameter(s). Did you mean "student"?
[javac] @Mapping(source = "java(student.toString())", target = "student")
[javac] ^
我试着经历这一切https://mapstruct.org/documentation/stable/reference/html/但不能简单的例子为我的用例
我如何将student
映射到它的string
表示
编辑:1
可以做吗
@Mapping(expression = new GSON().toJson(clazz.getStudent()), target = "student")
School mapClassToSchool(@NonNull Class class);
如果要使用表达式,则必须使用Mapping#expression
。无论您在表达式中定义什么,它都将在生成的代码中一一设置。
例如
@Mapping(expression = "java(clazz.getStudent().toString())", target = "student")
School mapClassToSchool(@NonNull Class clazz);
另一种选择是定义Student
和String
之间的映射方法,这样就不需要为学生定义自定义@Mapping
。
例如
School mapClassToSchool(@NonNull Class clazz);
default String mapStudentToString(Student student) {
return student != null ? student.toString() : null;
}
请注意,class
是Java保留字。
- 这不会编译:
School mapClassToSchool(@NonNull Class class)
- 请改用
clazz
:School mapClassToSchool(@NonNull Class clazz)