Java Converting Classes

橙三吉。 提交于 2019-12-08 02:20:23

问题


I have a class like:

Student
-name
-surname
-address
-number

and I have a DTO for it like:

StudentDTO
-name
-surname
-number

I will send my student class to another class just with name, surname and number fields(I mean not with all fields) and I decided to name it as DTO (I am not using serializing or etc. just I send this class's object as parameter to any other class's methods).

However lets assume that I have a line of code like that:

getAllStudents();

and it returns:

List<Student>

but I want to assign it to a variable that:

List<StudentDTO>

How can I convert them easily?

PS: I can't change my getAllStudents(); method's inside. I have list of students and want a fast and well-designed way to convert a list of objects into another list of objects.


回答1:


public StudentDTO convert() {
    StudentDTO newDTO = new StudentDTO(name, surname, number);
    return newDTO;
}

And you can implement this as a public method.

This, obviously, would be abstracted out into a larger convert method that could do batch processing. Another alternative would be to implement Cloneable and create a specific implementation just for Student -> StudentDTO.

Iterative example:

List<StudentDTO> myList = new ArrayList<>();
    for (Student s : collection) {
        myList.add(s.convert());
    }
    return myList;



回答2:


Use Apache commons-beanutils:

PropertyUtils.copyProperties(studentDtoBean, studentBean);



回答3:


You could try to change the StudentDTO to extend Student

public StudentDTO extends Student {
}

Remember that you could have the address attribute but no need to use it. If you can do it, then just change the result of your method to:

public List<? extends Student> getAllStudents() {
    List<StudentDTO> lsStudentDTO = new ArrayList<StudentDTO>();
    //fill the list...
    return lsStudentDTO;
}

EDIT:

You're not changing the code inside, you're changing the method definition :). Also, you can always extend the methods, maybe to something like

public List<? extends Student> getAllStudentsDTO() {
    //maybe you should add another logic here...
    return getAllStudents();
}

If you can't even change this behavior, just go with @DavidB answer.




回答4:


You can extends Student from StudentDTO:

public class StudentDTO {
    name;
    surname;
    number;
}

public class Student extends StudentDTO {
    address;
}

Than you can do:

List<StudentDTO> dtoList = new ArrayList<StudentDTO>(getAllStudents());


来源:https://stackoverflow.com/questions/10785919/java-converting-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!