Reputation: 3234
Here I am facing some difficulties while running the java reflection code i can't access dynamically changed field values in run time using reflection in java here i am putting my code complete code snippets with outputs and expected outputs
Here is my Reflection Class
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test1 {
public void reflect() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
TestJava instance = new TestJava();
Class<?> secretClass = instance.getClass();
// Print all the field names & values
Field fields[] = secretClass.getDeclaredFields();
System.out.println("Access all the fields");
for (Field field : fields) {
System.out.println("Field Name: " + field.getName());
if(field.getName().equals("i")) {
field.setAccessible(true);
System.out.println("For testing" +" "+field.get(instance) + "\n");
}
field.setAccessible(true);
System.out.println(field.get(instance) + "\n");
}
}
public static void main(String[] args) {
Test1 newHacker = new Test1();
TestJava secret = new TestJava();
try {
secret.increment();
newHacker.reflect();
secret.increment();
newHacker.reflect();
secret.increment();
newHacker.reflect();
secret.increment();
newHacker.reflect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here i am accessing the private variables from this class
public class TestJava {
private int i;
public void increment() {
i++;
System.out.println("Testing i value" +" "+ i);
}
}
The Out put of this program is
Testing i value 1
Access all the fields
Field Name: i
For testing 0
0
Testing i value 2
Access all the fields
Field Name: i
For testing 0
0
Testing i value 3
Access all the fields
Field Name: i
For testing 0
0
Testing i value 4
Access all the fields
Field Name: i
For testing 0
0
But the expected result is
Testing i value 1
Access all the fields
Field Name: i
For testing 1
1
Testing i value 2
Access all the fields
Field Name: i
For testing 2
2
Testing i value 3
Access all the fields
Field Name: i
For testing 3
3
Testing i value 4
Access all the fields
Field Name: i
For testing 4
4
Upvotes: 2
Views: 405
Reputation: 223023
Your Test1.reflect
uses a different instance of TestJava
from the secret
in main
. (Notice there are two places where new TestJava()
is called.) So calling secret.increment()
won't affect the instance of TestJava
used by Test1.reflect
.
But if you did this:
public class Test1 {
public void reflect(TestJava instance) throws IllegalAccessException, InvocationTargetException {
// Everything in your original method minus the first line
}
// ...
}
and then used the following in main
:
secret.increment();
newHacker.reflect(secret);
then things should behave as you expect.
Upvotes: 3