lundi 16 avril 2018

Change specific fields of a class in a nice way without reflection

I need to convert many (but not all) fields of objects that are in a Request class and I'm trying to do it in a nice way. From time to time field that need's to be converted are changing.

This is how Request class looks like:

public class Request {
    private FinancialParameters financialParameters;
    private AdditionalParameters additionalParameters;
}

public class FinancialParameters {
    private BigDecimal financialParam1;
    private BigDecimal financialParam2;
    (...)
    private BigDecimal financialParam99;
    private BigDecimal financialParam100;
}

public class AdditionalParameters {
    private BigDecimal additionalParam1;
    private BigDecimal additionalParam2;
    (...)
    private BigDecimal additionalParam99;
    private BigDecimal additionalParam100;
}

This is how I am doing it right now. And this takes hundreds lines of code. And it's difficult to change converted fields without mistake.

class ParamConverter {

    public Request convert(Request request){

    request.getFinancialParameters().setFinancialParam1(convert(request.getFinancialParameters().getFinancialParam1()));
    request.getFinancialParameters().setFinancialParam3(convert(request.getFinancialParameters().getFinancialParam3()));
    request.getFinancialParameters().setFinancialParam5(convert(request.getFinancialParameters().getFinancialParam5()));
    request.getFinancialParameters().setFinancialParam6(convert(request.getFinancialParameters().getFinancialParam6()));
    request.getAdditionalParameters().setAdditionalParam2(convert(request.getAdditionalParameters().getAdditionalParam2()));
    request.getAdditionalParameters().setAdditionalParam3(convert(request.getAdditionalParameters().getAdditionalParam3()));
    request.getAdditionalParameters().setAdditionalParam8(convert(request.getAdditionalParameters().getAdditionalParam8()));
    request.getAdditionalParameters().setAdditionalParam9(convert(request.getAdditionalParameters().getAdditionalParam9()));
    request.getAdditionalParameters().setAdditionalParam10(convert(request.getAdditionalParameters().getAdditionalParam10()));
    (...)
    return request;
    }
}

Is there a way to do it better ? My only idea is to make a list of fields that needs to be changed and change it using reflection. For example:

List<String> filedsToChange = Arrays.asList(
"FinancialParameters.financialParam1",
"FinancialParameters.financialParam3",
"FinancialParameters.financialParam5",
"FinancialParameters.financialParam6",
"AdditionalParameters.AdditionalParam10",
);

But can it be done nicer and without reflection ? Can it be done by annotating fields with custom annotation?





Aucun commentaire:

Enregistrer un commentaire