gpt4 book ai didi

Diamond 运算符中的 Java 传递类变量

转载 作者:行者123 更新时间:2023-12-02 14:55:12 24 4
gpt4 key购买 nike

我对一个Java项目有疑问:

public class example {

public Data getData() {
List<Users> users = usersService.findByClinicId(id);
Type targetListType = new TypeToken<List<UserDTO>>() {}.getType();
List<UserDTO> usersDTO = modelMapper.map(users, targetListType);

List<Personas> profesionales = personasService.findProfesionalsByClinicId(id);
targetListType = new TypeToken<List<PersonaDTO>>() {}.getType();
List<PersonaDTO> profesionalesDTO = modelMapper.map(profesionales, targetListType);

List<Personas> auxiliares = personasService.findAuxiliarsByClinicId(id);
targetListType = new TypeToken<List<PersonaDTO>>() {}.getType();
List<PersonaDTO> auxiliaresDTO = modelMapper.map(auxiliares, targetListType);

List<Prescripciones> prescripciones = prescripcionesService.findProfesionalsByClinicId(id);
targetListType = new TypeToken<List<PrescriptionNameDTO>>() {}.getType();
List<PrescriptionNameDTO> prescripcionesDTO = modelMapper.map(prescripciones, targetListType);

profesionales = entityToDTO(PersonaDTO.class, profesionales);

...
}

private <T> List<T> entityToDTO(Class<T> clazz, List<T> list) {
Type targetListType = new TypeToken<List<clazz>>() {}.getType();
List<PersonaDTO> auxiliaresDTO = modelMapper.map(list, targetListType);

}
}

想法是使用 entityToDTO 函数减少 getData 函数的代码。

我遇到的问题是:

  • entityToDTO 方法中,我想在 TypeToken 第一个参数中传递我想要的列表类型,但它不接受列表,其中 clazz 是具有类名的变量。

有没有办法在 List 菱形运算符内部传递一个具有我要使用的类类型的变量?

更新:想法是减少 getData 函数的行数。

最佳答案

为什么不传递 Type 呢?

private <T> List<T> entityToDTO(Type type, List<T> list) {
return modelMapper.map(list, type);
}

而在调用方,例如:

Type typeToUse = TypeToken.getParameterized(List.class, UserDTO.class).getType();

关于Diamond 运算符中的 Java 传递类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53298589/

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