Search code examples
javapolymorphism

How to create a request mapping dynamically


I need to create a mapper object based on the input type, is there a simple solution without switch case or if else conditions? Below is an example. Can you please help me to provide a simple working example for this?

Mapper mapper = null;
if(requestType=="AAA"){
    mapper = RequestMapperAAA.createTypeRequest(inputpayload);
} else if(requestType=="BBB"){
    mapper = RequestMapperBBB.createTypeRequest(inputpayload);
} else if(requestType=="CCC"){
    mapper = RequestMapperCCC.createTypeRequest(inputpayload);
} else if(requestType=="DDD"){
    mapper = RequestMapperDDD.createTypeRequest(inputpayload);
}  so on.. upto 20 input types

Solution

  • I will give a more detailed answer here, by responding to you question about using reflection. There is a good example here if you want to use reflection.

    You don't have to implement reflection to do this. The response of @Thiyadu is good also. Instead if you want to use factory pattern with reflection, I will suggest you to use a Dependency Injection framework such as Spring. The reflection phase is already made for you by Spring.

    An example with Spring will be the following:

    public interface Mapper {
        
    }
    

    RequestMapperAAA.java

    @Component("AAA")
    public class RequestMapperAAA implements Mapper {
    
    }
    

    RequestMapperBBB.java

    @Component("BBB")
    public class RequestMapperBBB implements Mapper {
    
    }
    

    RequestMapperCCC.java

    @Component("CCC")
    public class RequestMapperCCC implements Mapper {
    
    }
    

    Usage:

    @Autowired
    private Map<String, Mapper> requestMapper;
    
    public void userRequestMapper() {
        Mapper requestAAA = requestMapper.get("AAA");
    }
    

    The good thing about Spring is that, it will automatically populate the Map for you.