我需要调用泛型函数并让它在任何对象和模式之间进行映射 . 对于这个用例,我们正在探索modelmapper . 我们正在考虑下面的例子
我的来源是Class列表 . 此类包含很少的属性,它是一个扁平结构 .
现在我的来源是扁平结构:
我有一个SourceList列表,其中包含Source列表 . Source有employeeid,employername,employeeid和employeename属性 .
它看起来如下:
public class Source {
String employerId;
String employerName;
String employeeId;
String employeeName;
//getters and setters here
}
public class SourceList{
List <Source> source;
//getters and setters here
}
以下课程是我的目标:
我有一个雇主类,其中有一个雇主列表 . 雇主类具有雇主属性和雇员列表 .
public class Employers {
List<Employer> employer;
//getters and setters here
}
public class Employer {
String employerId;
String employerName;
List <Employee> employee;
//getters and setters
}
public class Employee {
String employeeId;
String employeeName;
//getters and setters
}
我想将Map SourceList映射到雇主映射 . 我想调用一个函数,它应该为我做的工作 .
Employers employers = modelMapper.map(sourceList, Employers.class);
我试过以下:然而它没有用 .
package com.mm.test;
public class MMTest {
public static void main(String args[]) {
SourceList sourceList = new SourceList();
List<Source> sourcel = new ArrayList<Source>();
Source source = new Source();
source.setEmployerId("1001");
source.setEmployerName("ABC Inc.");
source.setEmployeeId("100100");
source.setEmployeeName("Ken");
sourcel.add(source);
source = new Source();
source.setEmployerId("1001");
source.setEmployerName("ABC Inc.");
source.setEmployeeId("100102");
source.setEmployeeName("Ben");
sourcel.add(source);
sourceList.setSourceList(sourcel);
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setSourceNamingConvention(NamingConventions.NONE)
.setDestinationNamingConvention(NamingConventions.NONE);
modelMapper.getConfiguration().setMatchingStrategy(
MatchingStrategies.STANDARD);
Employers employers = modelMapper.map(sourceList, Employers.class);
System.out.println("EmployerID "
+ employers.getEmployer().get(0).getEmployerId());
System.out.println("Done");
}
}
是否可以使用模型映射器从上面的源到目标的这种映射 . 上面返回了一个null雇主对象 . 我不想处理属性级别映射,因为我希望映射非常通用 . 我可以稍后将任何对象和Schema传递给map() .