Better way of doing object conversion from one type to another?

78 Views Asked by At

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.

1

There are 1 best solutions below

2
Reilas On BEST ANSWER

"... 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? ..."

Rather than generics, utilize a class hierarchy.

Delegate each if-statement from the corresponding class.

abstract class Request {
    abstract Object get();
    boolean isConfig() { return this instanceof ConfigRequest; }
    boolean isDecision() { return this instanceof DecisionRequest; }
}

class ConfigRequest extends Request {
    @Override
    Config get() {
        Config config = new Config(); //create JPA object to copy properties into from request body
        BeanUtils.copyProperties(request, config);
        return config;
    }
}

class DecisionRequest extends Request {
    @Override
    Decision get() {
        Decision decision = new Decision();
        BeanUtils.copyProperties(request, decision);
        return decision;
    }
}

Then, simply return the get call.

public static Object from(Request request) {
    if(ObjectUtils.isEmpty(request)) return null;
    return request.get();
}