Does the Java ClassLoader load inner classes?

后端 未结 5 1591
迷失自我
迷失自我 2020-12-08 10:50

If I have a inner class declaration such as:

Class A {
    public static class B {
    }
}

followed by:

Class impl         


        
5条回答
  •  温柔的废话
    2020-12-08 11:09

    The code below is runnable and can illustrate some of the other answers:

    public class Outer
    {
    
       private static final String TEST01 = "I'm TEST01";
    
       static
       {
            System.out.println("1 - Initializing class Outer, where TEST01 = " + TEST01);
       }
    
       public static void main(String[] args)
       {
           System.out.println("2 - TEST01       --> " + TEST01 );
           System.out.println("3 - Inner.class  --> " + Inner.class);
           System.out.println("5 - Inner.info() --> " + Inner.info() );
       }
    
       private static class Inner
       {
    
           static
           {
              System.out.println("4 - Initializing class Inner");
           }
    
           public static String info()
           {
               return "I'm a method in Inner";
           }
        }
    }
    

    Please, pay attention to the sequence numbers, especially in this line:

    System.out.println("5 - Inner.info() --> " + Inner.info() );
    

    When you run the program you will see the following result on the console:

    1 - Initializing class Outer, where TEST01 = I'm TEST01
    2 - TEST01       --> I'm TEST01
    3 - Inner.class  --> class com.javasd.designpatterns.tests.Outer$Inner
    4 - Initializing class Inner
    5 - Inner.info() --> I'm a method in Inner
    

    A little more detail for each step:

    1 - 'Outer' is initialized when you Run the program. The static variable TEST01 is initalized before static block. Inner is not initialized.

    2 - The 'main' method is called and shows the value of 'TEST01'; then,

    3 - The System.out shows reference to 'Inner'. Inner is not initialized, but it was loaded (that's why it has reference in the memory model).

    4 - Here's the most interesting part. Because the System.out needs to access the 'info()' method in 'Inner' ( Inner.info() ), the 'Inner' class should be initialized before returning the result of the 'info()' method. That's why this is the step 4.

    5 - Finally, the System.out has all data it needs to show, and then the last line is showed on the console.

    So, as it was well pointed by @sotirios-delimanolis ( Does the Java ClassLoader load inner classes? ) loading a class is different from initializing it.

提交回复
热议问题