如何在java中使用反射递归地获得所有实例变量名称和值



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

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

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

我想这段代码可能会有所帮助。我还没有添加处理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());
            }
        }
    }
}

希望对你有帮助。

另一个使用反射获取name值的简单示例:

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

相关内容

  • 没有找到相关文章

最新更新