user2319311
user2319311

Reputation: 111

How do I get all the instance variable names and values recursively using reflection in java

Basically I need to print all the instance variable names and their values in a name value pair format recursively. Say my class structure is as below

public class SomeClass{

private String classDescription;
private Animals animals;
private Birds birds;
private List<Insects> insects;
private Map<String, Reptiles> others;

}

public class Animals{

private Dogs dogs;
private Cats cats;
private List<Mammals> mammalsList;

}

public class Dogs{
private String variable1;
private long variable2;
}

For the above class structure where I have chain of object references, I need to print the instance variable name and the corresponding values recursively. Code would be helpful.

Upvotes: 1

Views: 5585

Answers (2)

user6018651
user6018651

Reputation:

One more simple example to get name value with reflection:

public void getNameValue() {
    try {
        RingtoneManager ringtoneManager = new RingtoneManager(this);
        Field field = RingtoneManager.class.getField("ACTION_RINGTONE_PICKER");
        String type = field.getType().getSimpleName();
        String name = field.getName();
        String value = (String)field.get(ringtoneManager);
        Log.e(TAG,type + " " + name + " = " + value);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 0

Rahul Bobhate
Rahul Bobhate

Reputation: 5082

I guess this code might help. I haven't added the functionality for processing Map, but it works with List:

public static void main(String[] args) throws ClassNotFoundException 
{
    SomeClass s = new SomeClass();
    Class c = s.getClass();
    getMembers(c);
}

public static void getMembers(Class c) throws ClassNotFoundException 
{
    Field[] fields = c.getDeclaredFields();

    for (Field f : fields) 
    {
        if (f.getType().isPrimitive() || f.getType().equals(String.class))
        {
            System.out.println(c.getSimpleName() + ": " + f.getName() + " is a "+ f.getType().getSimpleName());
        }
        else 
        {
            if (Collection.class.isAssignableFrom(f.getType())) 
            {
                String s = f.toGenericString();
                String type = s.split("\\<")[1].split("\\>")[0];
                Class clazz = Class.forName(type);
                System.out.println(c.getSimpleName()+ ": "+ f.getName()+ " is a collection of "+ clazz.getSimpleName());
                getMembers(clazz);
            }
            else
            {
                System.out.println(c.getSimpleName() + ": " + f.getName() + " is a "+ f.getType().getSimpleName());
                getMembers(f.getType());
            }
        }
    }
}

Hope that helps.

Upvotes: 6

Related Questions