0

I was using the JExcel Plugin and i was noticing that i was writing the same code for a different set of objects. (Example shown below).

loanProfileListSheet.addCell(new label(0,rowNum,loanProfileView.getBorrowersList().getBorrowerPartnerId()));
loanProfileListSheet.addCell(new Label(1,rowNum,loanProfileView.getBorrowersList().getFirstName() + " " +   loanProfileView.getBorrowersList().getLastName()));

Now I want to know if there is an optimal way to pass a generic object to a utility method which would give me the object i need (so instead of writing somthing like loanProfileView.getBorrowersList().getFirstName(), i would have a util as such

Workbook getWorkBook (List<Object> objectList, List<String> attributes, Hashmap<String, String> attributeHeaders)

This way i would be able to pass any set of objects and get an excel workbook

Arvind Sridharan
  • 3,885
  • 4
  • 29
  • 54

1 Answers1

0

You could use reflection with Apache Commons / BeanUtils to make a generic method. However, I'm generally averse to using reflection in this way. It has a lot of down sides like renaming fields in you IDE does not refactor the code correctly and finding usages does not work well. Which makes it hard for otehr develoeprs (or yourself in a few months time) to understand the code.

I'd suggest you just make the code simpler when you see duplication of code.

E.g.

BorrowersList bl = loanProfileView.getBorrowersList();
WorksheetUtil.createCell(loanProfileListSheet, 0, rowNum, bl.getBorrowerPartnerId());
WorksheetUtil.createCell(loanProfileListSheet, 1, rowNum, bl.getFullName());

where you define getFullName() as

return firstname+" "+lastname;

and you define createCell as a 1 line util that does something like this

loanProfileListSheet.addCell(new Label(colNum,rowNum,param));

If you really want to go down the relection route, here is a post that covers what you need: Java Reflection Beans Property API

Community
  • 1
  • 1
Bruce Lowe
  • 6,063
  • 1
  • 36
  • 47