2

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).

3
  • Are the objects going to be generic, or is there only one class you're writing to the template? Commented Sep 24, 2012 at 20:39
  • Its only one class thats going to be written in the template. Commented 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. Commented Sep 24, 2012 at 20:51

1 Answer 1

2

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));
                }
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.