gpt4 book ai didi

Java 反射无法访问动态更改的私有(private)字段值

转载 作者:行者123 更新时间:2023-11-30 08:18:31 25 4
gpt4 key购买 nike

我在运行 java 反射代码时遇到了一些困难我无法在运行时使用 java 中的反射访问动态更改的字段值在这里我将我的代码完整代码片段与输出和预期输出

这是我的反射(reflection)课

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();

}

}


}

我在这里访问这个类的私有(private)变量

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);

那么事情应该如你所愿。

关于Java 反射无法访问动态更改的私有(private)字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27560247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com