mardi 22 octobre 2019

Validating an object with properties all of type String checking that they will be able to be parsed to the correct data type

I have an entity that is populated directly from an Excel file so every property is of type String. I am then mapping from this property to an actual entity that has all of the correct data types set using parses with try catch. For example:

InputEntity:

public class ProductInput {
   String name;  
   String color;  
   String price;  
   String date;
}

ActualEntity:

public class Product {
   String name;  
   String color;  
   Double price;  
   Date date;
}

Prior to doing the actual mapping I would like to log any errors to the database using an Error class I created.

The ultimate goal would be to make sure each value coming from the InputEntity is not null or empty and is the correct type (able to be set in the Actual Entity without any error). I want to use reflection to loop through the fields of the Product class and find the matching field on the ProductInput class. Then checking its value with the correct parse function to make sure it will eventually be able to be set in the Product entity. If there is an error I am going to create an error record that includes the property name that failed and store it in the database saying which input field has a problem.

Is reflection the correct way to go about this? I want the function to be generic enough to handle any classes as the input and actual assuming the properties of the input entity will always be string and the property names will match.

I was thinking somewhere along the lines of:

public validateFields(Class<T> inputClass, Class<T> destinationClass) {
    Field[] inputFields = inputClass.getDeclaredFields();
    Field[] destinationFields = destinationClass.getDeclaredFields();

    for (Field field: destinationFields) {
        // Check for same field in inputClass
        // If it exists confirm value of field is not null or empty
        // Additionally confirm the value of field can be parsed to the type of the destinationField
        // Create error entity with property name if there is a problem
    }
}




Aucun commentaire:

Enregistrer un commentaire