[英]Using Java reflection, can I access a private field of type private static nested class?
[英]Java reflection can't access dynamically changed private field values
这里我在运行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
您的Test1.reflect
使用来自main
的secret
的不同TestJava
实例。 (注意,有两个地方调用了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
使用以下内容:
secret.increment();
newHacker.reflect(secret);
然后事情应该像你期望的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.