2

I'm trying to get the member names of a class in Java. For instance, let's say I have the class:

class Dog
{
    private int legs = 4;
    private int ears = 2;
}

Is there anyway I can get a list of field names along with their types, such as

{ "legs" : "int", "ears" : "int" }.

Note I wrote the example result in JSON for convenience, but I'm doing it in Java.

fge
  • 119,121
  • 33
  • 254
  • 329
Jason
  • 13,563
  • 15
  • 74
  • 125
  • 4
    what you are asking for is called [reflection](http://docs.oracle.com/javase/tutorial/reflect/index.html) – Oren Jan 14 '13 at 15:17

2 Answers2

8

Use Class#getDeclaredFields(): -

for(Field f : Dog.class.getDeclaredFields()) {
    f.setAccessible(true);
    String name = f.getName();
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
AlexR
  • 114,158
  • 16
  • 130
  • 208
3
Field[] fields = Dog.class.getFields();

and call getName() for each element

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101