类加载器如何加载静态变量的说明 [英] Explanation of how classloader loads static variables

查看:64
本文介绍了类加载器如何加载静态变量的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这是Java上的一个新手问题,但我似乎无法解决。

Ok so this is a newbie question on java, but i can't seem to get my head around it.

我的类中有以下代码

private static final String [] LIST_CODE = gerarListCode();
private static final int [][] LIST_INTEGER = new int [][] {
        {947,947}, {110,103}, 
        {947,958}, {110,120}, 
        {947,954}, {103,107}, 
        {947,967}, {110,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而使我初始化异常

This code is giving me a initialization exception due to a nullpointerexception in the following line

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

似乎变量LIST_INTEGER当时为空。

Seems the variable LIST_INTEGER is null at that time.

有人可以解释为什么吗?是

Can someone explain why? is the classloader process linear, in other words, does it invoke the method before fully loading all the other variables?

推荐答案

是吗,是,类加载器过程是线性的吗,换句话说,它是否在完全加载所有其他变量之前调用该方法?简而言之,它是线性的。

Yes, in short, it is linear.


编译器实际上所做的是
在内部生成单个类
初始化例程,它将
的所有静态变量初始化器
和所有静态初始化器
代码块组合在一起,并按顺序使它们
出现在类声明中。 b单个初始化过程仅在第一次加载
类时自动运行

"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。

Taken from Java in a nutshell.

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

您应该定义变量,然后在静态intitializer块中对其进行初始化。正确的顺序,也可以按如下所示交换语句的顺序:

You should define the variables and then initialize them in a static intitializer block in the correct order, or you could swap the order of the statements as follows:

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

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

这篇关于类加载器如何加载静态变量的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆