这里我在运行java反射代码时面临一些困难我无法在运行时使用java中的反射访问动态更改的字段值这里我将我的代码完整代码片段与输出和预期输出
这是我的反思课
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();
}
}
}
我在这里访问这个类的私有变量
public class TestJava {
private int i;
public void increment() {
i++;
System.out.println("Testing i value" +" "+ i);
}
}
此计划的输出
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
但预期的结果是
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
答案 0 :(得分:3)
您的Test1.reflect
使用TestJava
中secret
的{{1}}的其他实例。 (请注意,有两个地方会调用main
。)因此调用new TestJava()
不会影响secret.increment()
使用的TestJava
实例。
但如果你这样做了:
Test1.reflect
然后在public class Test1 {
public void reflect(TestJava instance) throws IllegalAccessException, InvocationTargetException {
// Everything in your original method minus the first line
}
// ...
}
中使用以下内容:
main
然后事情应该像你期望的那样。