dimanche 7 avril 2019

Use reflection to access property based on parameter received - Java

I'm developing a project in Spring, and I have a configuration file which maps areas to sites, something like:

===========
Areas Mapper
===========

Sites:
    USA:
        - Arizona
        - Florida
        - New York
        - Texas
    Europe:
        - Germany
        - Russia
        - Poland

Now, I get the area as a parameter from an API call, and I need to return a list of sites based on this param.

I was wondering, if using reflection in this case in order to access the list of sites dynamically is the right way to do it? and if so, how would you do it?

This is what I've done so far:

Configuration Class:

@ConfigurationProperties(prefix = "Sites")
@Component
@Data
public class AreasToSitesMapperConfig {

    protected List<String> usa;
    protected List<String> europe;
    protected List<String> australia;
}

Mapper Class:

@Component
public class AreasToSitesMapper {

    @Inject
    private AreasToSitesMapperConfig areasToSitesMapperConfig;

    public List<String> getSitesForArea(String area) throws NoSuchFieldException {
        Field field = AreasToSitesMapperConfig.class.getDeclaredField(area);
        field.setAccessible(true);
        return field.get(this);

        //Of course I can implement it as follows, but I'm not sure this is the right way to do it :  
        if (area == "USA") return areasToSitesMapperConfig.usa ......
    }
}

This is the call from the service:

List<AreaDataDAO> areaDataList = areasRepository.getDataBySiteInAndDateBetweenOrderByDateDesc(
            areasToSitesMapper.getSitesForArea(area),     
        );

As you can see, 'area' is passed to 'getSitesForArea' function, and based on this parameter I need to return the relevant list.





Aucun commentaire:

Enregistrer un commentaire