如何解决静态嵌套数据类结构中嵌入对象数组的赋值与空指针问题
静态嵌套结构中对象数组空指针问题的解决
报错原因
代码触发空指针是两个设计问题叠加导致的:
- 数组初始化仅开辟了长度为3的引用存储空间,未给数组内每个元素分配实际对象实例。
new this_thingy[3]只是创建了一个长度为3的引用数组,数组内每个位置默认值为null,直接访问classArray[0].thing自然会抛出空指针。 - 嵌套的
this_thingy是非静态内部类,会隐式持有外部类InnerClass的实例引用,哪怕后续手动赋值数组元素,没有外部实例的情况下也无法直接实例化这个类,会直接触发编译错误。
修正方案
- 将
this_thingy调整为静态嵌套类,消除它对外部InnerClass实例的隐式依赖,满足静态上下文的实例化要求。 - 为静态数组
classArray添加静态初始化块,遍历数组长度为每个位置实例化this_thingy对象,并调用init()方法完成字段赋值。 - 注意
init()是普通成员方法而非类构造方法,必须手动调用才能给字段赋值,不调用的话类内的thing、other字段默认仍为null。
注意:如果业务要求必须保留
this_thingy为非静态内部类,实例化时需要先获取对应外部类InnerClass的实例,再通过外部实例创建内部类对象,写法为classArray[i] = new DataClass.InnerClass().new this_thingy();,这种写法更适合需要内部类持有外部实例引用的场景,静态嵌套结构下优先用静态内部类更简洁。
修正后可直接运行的代码
class test { public static class DataClass { static String thing = new String("thing 1"); public static class InnerClass { static String thing = new String("thing 2"); // 改为静态嵌套类,移除对外部实例的隐式依赖 public static class this_thingy { String thing; String other; void init() { thing = "thing 3"; other = "other"; } } public static this_thingy[] classArray = new this_thingy[3]; // 静态初始化块填充数组元素 static { for (int i = 0; i < classArray.length; i++) { classArray[i] = new this_thingy(); classArray[i].init(); } } } } public static void main(String[] args) { System.out.println(DataClass.InnerClass.thing); System.out.println(DataClass.InnerClass.classArray[0].thing); System.out.println(DataClass.InnerClass.classArray[0].other); } }
运行输出
thing 2 thing 3 other
内容的提问来源于stack exchange,提问作者Rod
相关产品推荐
相关产品推荐

