gpt4 book ai didi

java - 如何从私有(private)静态内部类访问变量

转载 作者:行者123 更新时间:2023-11-30 02:48:37 24 4
gpt4 key购买 nike

我有一个这样的类结构:

public class Outer{
private Outer.Inner personal;
public Outer(){
//processing.
//personal assigned value
}
........
private static class Inner {
private final Set<String> innerPersonal;
Inner(){
innerPersonal=new HashSet<>();
//populate innerPersonal
}
}
}

我在程序中得到了一个 Outer 对象,如何使用反射在我的程序中提取innerPersonal

最佳答案

由于您想要在 Outer 外部执行代码,因此不能使用 Outer.Inner.class 来引用您的 静态内部类它是 private,所以在这里我提出了一种方法,首先获取字段 personal 的值,然后调用 getClass()字段的返回值(假设它不是 null),以最终访问此内部类,该内部类还允许访问其字段innerPersonal .

Outer outer = ...
// Get the declared (private) field personal from the public class Outer
Field personalField = Outer.class.getDeclaredField("personal");
// Make it accessible otherwise you won't be able to get the value as it is private
personalField.setAccessible(true);
// Get the value of the field in case of the instance outer
Object personal = personalField.get(outer);
// Get the declared (private) field innerPersonal from the private static class Inner
Field innerPersonalField = personal.getClass().getDeclaredField("innerPersonal");
// Make it accessible otherwise you won't be able to get the value as it is private
innerPersonalField.setAccessible(true);
// Get the value of the field in case of the instance personal
Set<String> innerPersonal = (Set<String>)innerPersonalField.get(personal);

关于java - 如何从私有(private)静态内部类访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39367746/

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