I need to find all 'missing' and extra fields for every dto's by their entities using reflection. For example.
I have
public class TestDto {
long id;
String name;
int age;
long personId;
String phone;
}
And Entity
public class TestEntity {
long id;
String name;
int age;
Person person;
String address;
}
person = personId(mapping). We don't need to print it like 'missing' field and 'extra' field.
Output: Missing fields for dto. Please add!: address; Extra fields for dto. Please remove! : phone;
i wrote
private final Map<String, String> fieldMappings = new HashMap<>();
fieldMappings.put("person", "personId");
Field[] dtoFields = auditDtoClass.getDeclaredFields();
Field[] entityFields = entityClass.getDeclaredFields();
List<String> missingFields = Arrays.stream(entityFields)
.filter(field -> !fieldMappings.containsKey(field.getName()) && Stream.of(dtoFields)
.noneMatch(dtoField -> dtoField.getName().equals(field.getName())))
.map(Field::getName)
.filter(field -> Arrays.stream(dtoFields)
.noneMatch(f -> f.getName().equals(field)))
.toList();
List<String> extraFields = Arrays.stream(dtoFields)
.filter(field -> !fieldMappings.containsValue(field.getName()) &&
!fieldMappings.containsKey(field.getName()) && Stream.of(entityFields)
.noneMatch(entityField -> entityField.getName().equals(field.getName())))
.map(Field::getName)
.filter(field -> Arrays.stream(entityFields)
.noneMatch(f -> f.getName().equals(field)))
.toList();
It's wrong.
Because programmer can add (private Person person field) in other entity without adding to dto and it didn't print it in missing fields.
I also think that we can link those fields
fieldMappings.put("person", "personId");
to the entity/dto classes but now I don't understand how.
I'd love to hear ideas on how to do this.