I have a list of objects and need to populate an excel using its attributes. Each cell will have an attribute of the java object. Now I was wondering if there is a generic of way of doing it. The attributes of the java object is either String and double and there is around 30 of these attributes. Do I have to get each attribute separately using the getter and then populate the cell or is there a more elegant way of doing it ( in a loop, using reflection etc).
-
Are the objects going to be generic, or is there only one class you're writing to the template?David B– David B2012-09-24 20:39:29 +00:00Commented Sep 24, 2012 at 20:39
-
Its only one class thats going to be written in the template.Jeff Fleming– Jeff Fleming2012-09-24 20:49:36 +00:00Commented Sep 24, 2012 at 20:49
-
Then I'd say the best way to do it is to write a method to output to the Excel file based on just that class. You could make a generic function with reflection, but I think that would fall under YAGNI.David B– David B2012-09-24 20:51:17 +00:00Commented Sep 24, 2012 at 20:51
Add a comment
|
1 Answer
Yes, you can do it with reflection. You first get a list of all declared fields of your class, then check its type and use reflection again to get value of that field from each instance in your list. Mind you, the fields returned are not guaranteed to be in any particular order, although staring from java 6 they actually are returned in declaration order.
for (Field field : Test.class.getDeclaredFields()) {
if (field.getType() == String.class) {
System.out.println(field.get(yourInstance));
}
}