报错java.lang.exceptionininitializererror异常

本文介绍了一种在Java中遇到的静态变量初始化错误,并提供了解决方案。通过将静态变量的初始化从静态代码块移至构造函数中,可以避免因初始化顺序不当导致的内存泄漏问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非常感谢此博主博客,助我解决了bug,博客地址如下
http://blog.youkuaiyun.com/kingzone_2008/article/details/45015301
最近出现了个这上面的异常,报错异常是说–>变量初始化出现问题,通常出现在静态变量尤其是单例模式。这种问题往往是初始化顺序不对造成的!

报错代码如下:

public class InvestPeopleRes {

    private static List<InvestPeople> investPeopleList ;

    //静态代码块 在jvm在加载类的时候,就已经在执行加载了
    static {
        investPeopleList = new ArrayList<>();
        investPeopleList.add(new InvestPeople("2016-04-06 23:15", 2000.00f, "135******41"));
        investPeopleList.add(new InvestPeople("2016-05-06 08:15", 100.00f, "133******85"));
        investPeopleList.add(new InvestPeople("2016-05-05 17:15", 12430.00f, "136******55"));
    }

    //外界方法调用时,返回对象
    public static List<InvestPeople> getInvestPeopleList() {
        return investPeopleList;
    }
}

即当程序在加载的时候,就会出现investPeopleList 对象的内存泄漏! 解决方案只需要解决investPeopleList对象初始化的问题即可!
方案如下:将investPeopleList 对象初始化放在构造器中其就ok

public class InvestPeopleRes {

    private static List<InvestPeople> investPeopleList ;
    //无参数构造器
    public InverstPeopleRes(){
 investPeopleList = new ArrayList<>();
        investPeopleList.add(new InvestPeople("2016-04-06 23:15", 2000.00f, "135******41"));
        investPeopleList.add(new InvestPeople("2016-05-06 08:15", 100.00f, "133******85"));
        investPeopleList.add(new InvestPeople("2016-05-05 17:15", 12430.00f, "136******55"));
}
    //外界方法调用时,返回对象
    public static List<InvestPeople> getInvestPeopleList() {
        return investPeopleList;
    }
}

更加详细的类的执行顺序,请参考博客
http://blog.youkuaiyun.com/kingzone_2008/article/details/45015301

以上!谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值