0
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");
        }
    }
}
6
  • 7
    What are you expecting to happen, and what happens instead? Commented Mar 31, 2015 at 9:45
  • I want to obtain the values of each field of my Angajat class using reflection Commented Mar 31, 2015 at 9:47
  • 1
    "and what happens instead? " Commented Mar 31, 2015 at 9:48
  • @Cristian, I suspect you want to find out the values of the fields on the objects in the angajati list? Commented Mar 31, 2015 at 9:48
  • 2
    "instead throws me an exception" well Java have many exceptions and they are caused by different problems so you should consider editting your question to include more info about them (like stacktrace). Commented Mar 31, 2015 at 9:54

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Consider adding fd[i].setAccessible(true) in case OP would want to read private fields.
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())
Feels kind of off topic for what's being asked. I like to keep my answers to the point.
OK, fair enough, but I will leave my comments just in case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.