mercredi 24 mai 2017

How to get all fields of a class

I have two classes with same number of fields and with same field names . the only different is their field Types.

what I need too do is to get all fields value from one class and put them into the other one .

public class PersonA {
    private String name;
    private String family;
    //here AddressDto package is com.test.project.employer
    private AddressDto addressDto;
    //here ContactInfo package is com.test.project.employer
    private List<ContactInfo> contactInfo;
}

public class PersonB {
        private String name;
        private String family;
        //here AddressDto package is com.test.project.customer
        private AddressDto addressDto; 
        //here ContactInfo package is com.test.project.customer
        private List<ContactInfo> contactInfo;
    }

there might be other Dtos inside outer Dtos too or Maps with Custom Dtos , so I need to manage all fields to be checked if there is an other dto inside or not !

what I have done already , works for Java classes and Primitive types like String , BigDecimal , int and ... but not for my application dtos .

here is my code :

PersonA personA = new PersonA();
PersonB personB = new PersonB();

Field[] aFields = personA.getClass().getDeclaredFields();

for (Field field : aFields){
    field.setAccessible(true);
    Field bField= personB.getClass().getDeclaredField(field.getName());
    httpField.setAccessible(true);
    Object value = field.get(personA);
    bField.set(personB, value);
}

what I am thinking of is to write it in recursive form. Is there any solution for my problem ?





Aucun commentaire:

Enregistrer un commentaire