Search code examples
javastatichashmapdaodto

Automatic detection of correct map


public class DAOHelper {

private static final Map<Class, Class> DTO_TO_DAO_MAP;
private static final Map<Class, Class> ACDTO_TO_ACDAO_MAP;


static {
    DTO_TO_DAO_MAP = new HashMap<Class, Class>();
    DTO_TO_DAO_MAP.put(EmployerDTO.class, EmployerDAO.class);

    ACDTO_TO_ACDAO_MAP = new HashMap<Class, Class>();
    ACDTO_TO_ACDAO_MAP.put(AcademicDTO.class, AcademicDAO.class);

}

public static BaseDAO<?> getDAO(Class dtoClass) {
    BaseDAO<?> dao = null;
    Class daoClass = ACDTO_TO_ACDAO_MAP.get(dtoClass); //here
    //rest of code  here

}

Class daoClass = ACDTO_TO_ACDAO_MAP.get(dtoClass); In this proportion of code, instead of ACDTO_TO_ACDAO_MAP how can I get the code to detect this automatically, so I don't do it manually for each one as it could be DTO_TO_DAO_MAP or others...


Solution

  • I would suggest using a naming convention and reflection:

    Assuming every DAO (FooDTO) has a corresponding DAO (FooDAO) in the same package, the code would look something like this (disclaimer - this is off the top of my head and may need a tweek or 2 to compile)

    public static BaseDAO<?> getDAO(Class dtoClass) {
    
        String dtoClassName = dtoClass.getName();
        String daoClassName = dtoClassName.replaceAll("DTO$", "DAO");
        Class daoClass =  Class.forName(daoClassName);
        retrun daoClass.newInstance(daoClass);
    }
    

    and of course this logic could be easily altered to accommodate different naming conventions or different packages.