Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

java - Explanation of how classloader loads static variables

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

I have the following code inside my class

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;
    }

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, in short, it is linear.

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

Taken from Java in a nutshell.

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

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(); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...