What should be passed to this method (Field # get (Object obj))?
After looking at the Java documentation here and reading the Oracle Tutorial , and also visiting this question here on SO , I'm still stunned that there actually is an argument Object
in Field#get(Object obj)
.
The process I am taking to get a field using Reflection is:
Field field = SomeClass.getClass().getDeclaredField("someField");
field.setAccessible(true);
What the object gives Field
. Now, to get the actual value of a field, you must use the Field#get(Object obj)
. The documentation for this method states the following about the parameter.
obj - the object from which the displayed field value should be retrieved
I have no idea what the parameter description means. Can someone explain to me what this argument is really asking for?
Thank.
source to share
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 reflect the value of a field bar
of f1
, you would call
field.get(f1); // returns 1
To reflect the value of a field bar
of f2
, you would call
field.get(f2); // returns 2
source to share
Try to run 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 receive as output:
1 2
Here variable field
refers to a variable value
from the class TestReflect
. But it value
is a variable, so each class object TestReflect
has its own variable value
. To get a variable value
, you need to specify which object you get it from and what the parameter is for.
source to share