I was implementing a generic kind of function which accepts a List<someClass>
and perform an operation on it, say creating an excel sheet for List<someClass>
. So such a method can be used by List<anyClass>
because we just need to iterate over the list elements and use Workbook.setCellValue(T value)
method. I have two approach for this problem which are as follows:
Using List<List> where Objects are nothing but fields
of someClass
.
public void genericMethodForExcel(List<List<Object>> list) {
for(List objects: list) {
for(Object obj: objects){
//now obj here is field of someClass object.
}
}
}
//how we convert List<someClass> to List<List<Object>>
List<List<Object>> object = someClassList.stream().map(obj->{
List<Object> list = new ArrayList<>();
list.add(obj.getName());
list.add(obj.getNumber());
return list;
}).collect(Collectors.toList());
//now calling the method
genericMethodForExcel(object);
Second approach for this problem is using Java Reflections:
//we pass List<?> to genericMethod
genericMethodForExcel(List<?> list);
public void genericMethodForExcel(List<?> list){
for(Object obj: list){
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field: fields) {
//now accessing field value using field.get(obj);
}
}
}
Which one of these approach is better and why??
Aucun commentaire:
Enregistrer un commentaire