加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 关于classloader如何加载静态变量的说明

发布时间:2020-12-14 05:27:20 所属栏目:Java 来源:网络整理
导读:好吧,这是一个关于 java的新手问题,但是我似乎并没有把握头脑. 我的课程中有以下代码 private static final String [] LIST_CODE = gerarListCode();private static final int [][] LIST_INTEGER = new int [][] { {947,947},{110,103},{947,958},120},954},
好吧,这是一个关于 java的新手问题,但是我似乎并没有把握头脑.

我的课程中有以下代码

private static final String [] LIST_CODE = gerarListCode();
private static final int [][] LIST_INTEGER = new int [][] {
        {947,947},{110,103},{947,958},120},954},{103,107},967},99,104}};

 private static String [] gerarListCode()
    {
        String [] listCode = new String [LIST_INTEGER.length];

        for (int i=0 ; i<LIST_INTEGER.length ; i++)
        {
           //do some stuff      
        }

        return listaUnicode;
    }

此代码由于在以下行中的nullpointerexception而给我一个初始化异常

String [] listCode = new String [LIST_INTEGER.length];

此时变量LIST_INTEGER为空.

有人可以解释为什么吗是类加载器进程的线性,换句话说,它是否在完全加载所有其他变量之前调用该方法?

解决方法

是的,简而言之,它是线性的.

“What the compiler actually does is to
internally produce a single class
initialization routine that combines
all the static variable initializers
and all of the static initializer
blocks of code,in the order that they
appear in the class declaration. This
single initialization procedure is run
automatically,one time only,when the
class is first loaded.”

简单来说,从Java开始.

http://www.developer.com/java/other/article.php/2238491

您应该定义变量,然后以正确的顺序在静态intitializer块中初始化它们,或者您可以如下交换语句的顺序:

private static final int [][] LIST_INTEGER = new int [][] { {947,104}};

private static final String [] LIST_CODE = gerarListCode();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读