문제

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.

도움이 되었습니까?

해결책

Use Class#getDeclaredFields(): -

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

다른 팁

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

and call getName() for each element

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top