I am converting objects that are coming through an API request body to JPA objects as below.
public class Converter {
public static <T> Object from(T request) {
if(ObjectUtils.isEmpty(request))
return null;
if(request instanceof ConfigRequest) {
Config config = new Config(); //create JPA object to copy properties into from request body
BeanUtils.copyProperties(request, config);
return config;
}
if(request instanceof DecisionRequest) {
Decision decision = new Decision();
BeanUtils.copyProperties(request, decision);
return decision;
}
.......
}
}
I have around 15 different request objects to work with (which will lead to 15 if blocks).
Is there a cleaner way of achieving the same goal with Generics or some other way I may have missed out?
TIA.
Rather than generics, utilize a class hierarchy.
Delegate each if-statement from the corresponding class.
Then, simply return the get call.