Shengjie
Shengjie

Reputation: 12786

How to pass the class fields in a method using reflection

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

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533530

Are you trying to use

for(Field field : getClass().getDeclaredFields()) {
    Object o = field.get(this);
    add(o);
}

Upvotes: 2

Vincenzo Maggio
Vincenzo Maggio

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

Jon Skeet
Jon Skeet

Reputation: 1500785

If you're trying to get the field values for the "current" instance (the instance your testMethod() method was called on), you just want to call Field.get with this as the target:

add(f.get(this));

Upvotes: 4

Related Questions