3

After looking at the Java documentation here, and reading an Oracle tutorial, as well as visiting this question here on SO, I am still dumbfounded as to what the Object argument in Field#get(Object obj) actually is.

The process that I take to get a field using Reflection is:

Field field = SomeClass.getClass().getDeclaredField("someField");
field.setAccessible(true);

Which gives the Field object. Now, to get the actual value of the field, you would use the Field#get(Object obj) method. The documentation for this method says the following about the parameter.

obj - object from which the represented field's value is to be extracted

I have no idea what the description of the parameter even means. Can someone explain to me what this argument is truly asking for?

Thanks.

Community
  • 1
  • 1
hmc_jake
  • 372
  • 1
  • 17

2 Answers2

5

Suppose you have a class Foo:

public class Foo {
    public int bar;
}

Now you can have multiple instances of this class:

Foo f1 = new Foo();
f1.bar = 1;
Foo f2 = new Foo();
f2.bar = 2;

To get the value of the field bar of f1 reflectively, you would call

field.get(f1); // returns 1

To get the value of the field bar of f2 reflectively, you would call

field.get(f2); // returns 2
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Try running this code:

import java.lang.reflect.Field;
public class TestReflect
{
  private int value;

  public static void main ( String[] args) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException
  {
    Field field = TestReflect.class.getDeclaredField("value");

    TestReflect objRed = new TestReflect();
    TestReflect objBlue = new TestReflect();

    objRed.value = 1;
    objBlue.value = 2;

    System.out.println( field.get(objRed) );
    System.out.println( field.get(objBlue) );
  }
}

You will get as output :

1
2

There the field variable is referencing the variable value from the class TestReflect. But value is an instance variable so each and every object of class TestReflect has its own value variable. To get the value variable you need to specify from which object you are getting it and that is what the parameter is for.

Anonymous Coward
  • 3,140
  • 22
  • 39