vendredi 16 février 2018

How to implement programmatically a function that receives an object and list of values ​that I want and return them to me on a map?

I would like to know how to perform a function that receives an object (object class), as well as a list of variables which correspond to properties of the object and return it on a map.

I understand that this could be done as reflection and generics or something similar but I can not do it.

For example :

Class client - id - name - surname

Class adress - id - country - capital

Client client = new Client(9,"Elon", "Musk");
Country country = new Country(3,"Spain","Madrid");

List<String> variables1 = Arrays.asList("id","name");
List<String> variables2 = Arrays.asList("country","capital");

Map<String,String> result1 = variablesCollector(client,variables1);
//should be return a map with "id" -> 9 , name -> "elon"
Map<String,String> result1 = variablesCollector(country,variables1);
//should be return a map with "country" -> "spain" , "capital"-> "madrid"

private Map<String, String> variablesCollector(Object o, List fields){

     //LOGIC WITH REFLECTION AND GENERIC
     return map;

}





Aucun commentaire:

Enregistrer un commentaire