Question

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.

Was it helpful?

Solution

Use Class#getDeclaredFields(): -

for(Field f : Dog.class.getDeclaredFields()) {
    f.setAccessible(true);
    String name = f.getName();
}

OTHER TIPS

Field[] fields = Dog.class.getFields();

and call getName() for each element

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top