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 Answer
This part is wrong:
Object o1 = fd[i].getType().newInstance();
Object o = fd[i].get(o1);
(because you end up looking at the fields of newly created objects.)
You probably want to do just
Object o = fd[i].get(a);
4 Comments
Pshemo
Consider adding
fd[i].setAccessible(true) in case OP would want to read private fields.Pshemo
Also it may be worth mentioning that since OP seems to know what enhanced-for-loop is (based on
for (Angajat a : angajati) fragment) Class c = a.getClass(); Field[] fd = c.getDeclaredFields(); for (i = 0; i < fd.length; i++) { can be replaced with simple for (Field f: a.getClass().getDeclaredFields())aioobe
Feels kind of off topic for what's being asked. I like to keep my answers to the point.
Pshemo
OK, fair enough, but I will leave my comments just in case.
angajatilist?