2

I have this class:

public class Person {

    private String name;
    private int age;

}

I want to make an Excel file, and before I put the values into the Excel sheet I need name and age as columns in the sheet. All I need to know is how to get the property names (and NOT the values).

So for example if I have:

name= "Marc"
age= 26

I want to get "name" and "age" first instead of "Marc" and 26. How do I do this?

Just to be clear, the name and number of properties can vary so I can't hardcode "name" and "age", I need some way to iterate and get it. I know how to iterate and put it into the sheet. All I need help with is how to get the property name.

The closest I've got is getDeclaredFields(), but then I can't get further, because I can't get anything from that Field type.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheStranger
  • 1,387
  • 1
  • 13
  • 35

5 Answers5

2

You can get field name. Here is an example:

Field[] allFields = Person.class.getDeclaredFields();
for(Field f:allFields) 
    System.out.println(f.getName());
Ismail H Rana
  • 351
  • 1
  • 9
1

You're on the right track. getDeclaredFields() returns a Field[]. Iterating over this array and accessing the getName() method on each Field should to the trick.

To use your example:

Person p = new Person();
Field[] fields = Person.class.getDeclaredFields();
for (Field field : fields) {
    boolean accessible = field.isAccessible();
    try {
        field.setAccessible(true);
        System.out.println(field.getName() + " - " + field.get(p));
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        field.setAccessible(accessible);
    }
}
a.deshpande012
  • 715
  • 7
  • 18
1

Person.class.getDeclaredFields()

it retun Field[] and you can get information for each Field.

1

This should work fine. Later you can iterate using the indices of field array to store/write the data.

Field[] fields = YourClassName.class.getFields();
darecoder
  • 1,478
  • 2
  • 14
  • 29
0

If you are not bound to use the class as it is, and to avoid using reflexion, I suggest you use a HashMap, so you can add key-value elements. This way you will have 'legal' access to both the name and the value. For example, you can map.put("name", "George"); and then use them as you please. You can check the details here https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html