1

基本上我需要以名称值对格式递归地打印所有实例变量名称及其值。说我的班级结构如下

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;
}

对于上面我有对象引用链的类结构,我需要递归地打印实例变量名称和相应的值。代码会很有帮助。

4

2 回答 2

5

我想这段代码可能会有所帮助。我没有添加处理功能Map,但它适用于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());
            }
        }
    }
}

希望有帮助。

于 2013-05-23T07:12:15.360 回答
1

通过反射获取名称值的另一个简单示例:

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();
    }
}
于 2016-08-03T16:15:18.810 回答