如何使用反射获取字段值?

时间:2015-03-31 09:43:43

标签: java

void showReflection() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    int i;
    for (Angajat a : angajati) {
        Class c = a.getClass();
        Field[] fd = c.getDeclaredFields();
        for (i = 0; i < fd.length; i++) {
            String name = fd[i].getName();
            Object o1 = fd[i].getType().newInstance();
            Object o = fd[i].get(o1);
            System.out.print(name + " " + o + "\n");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这部分错了:

Object o1 = fd[i].getType().newInstance();
Object o = fd[i].get(o1);

(因为你最终会看到新创建的对象的字段。)

你可能只想做

Object o = fd[i].get(a);