Reputation: 12786
class A {
private TypeA a;
Private TypeB b;
...
Private TypeZ z;
...getters/setters...
public add(Object o) {
//blablabla
}
public testMethod() {
add(a);
add(b);
add(c);
......
add(z);
/** here instead of calling add(a), add(b), add(c) one by one, I want to use reflection.
** something like:
** foreach(Field f : getDeclaredFields()) {
** add(f.getTheObjectReference()); <-- I made this method "getTheObjectReference" up
** }
**/
}
}
so in this example, I can use getDeclaredFields get all the fields Field[a-z], but once I have the Field object, how do I convert that to the actual object reference? there is no method from Field class called "getTheObjectReference". Any ideas?
Upvotes: 0
Views: 776
Reputation: 533530
Are you trying to use
for(Field field : getClass().getDeclaredFields()) {
Object o = field.get(this);
add(o);
}
Upvotes: 2
Reputation: 3869
What you are trying to do is impossible because the Field instance refers to a generic class method, not a specific class instance method!
Upvotes: 0