27

If I have a inner class declaration such as:

Class A {
    public static class B {
    }
}

followed by:

Class<?> implClass = getClass().getClassLoader().loadClass("A");

Will the A$B inner class be loaded as well? What if the B inner class was not declared as "static" ?

Janik Zikovsky
  • 3,086
  • 7
  • 26
  • 34

5 Answers5

34

Once the code is compiled, there's no such thing as an inner class. If you look at the results of javac, you'll see two files:

A.class
A$B.class

So class B is not loaded when A is loaded, B just happens to be defined in A.


Edit

For example, given these two files,

package kuporific;

public class A {
    private static class B {}
    private class C {}
}

and a build.gradle file (for convenience):

apply plugin: 'java'

First, build by running gradle build. Then, unzip the resulting JAR file (located in build/libs):

├── META-INF
│   └── MANIFEST.MF
└── kuporific
    ├── A$B.class
    ├── A$C.class
    └── A.class

Opening each file (in IntelliJ, for example), reveals what the compiler has done:

  • A.class:

    package kuporific;
    
    public class A {
        public A() {
        }
    
        private class C {
            public C() {
            }
        }
    
        private static class B {
            public B() {
            }
        }
    }
    
  • A$B.class:

    package kuporific;
    
    class A$B {
        private A$B() {
        }
    }
    
  • A$C.class:

    package kuporific;
    
    import kuporific.A;
    
    class A$C {
        private A$C(A this$0) {
            this.this$0 = this$0;
        }
    }
    

Notice that

  1. A$B does not have a reference to its parent, A, while A$C does. This is because the former is a static inner class, and the latter is not, and
  2. both A$B and A$C are now package private classes.

This is how non-static inner classes are able to directly reference their parent instance's fields and methods, and vice versa. (Any private fields of the parent class referenced in an inner class are made package private as well.)

Next, let's see what effect loading class A has on A$B and A$C.

First, add the following Java class:

package kuporific;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        Main.class.getClassLoader().loadClass("kuporific.A");
    }
}

Now add the following to the build.gradle file:

apply plugin: 'application'
mainClassName = 'kuporific.Main'
applicationDefaultJvmArgs = ["-verbose:class"]

The -verbose:class outputs all classes that are loaded by the JVM (see Java - Get a list of all Classes loaded in the JVM).

Run gradle run on the command line (which runs the main method of Main); the output (with my added notes) is

:compileJava
:processResources UP-TO-DATE
:classes
:run
[Opened /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Object from /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/jre/lib/rt.jar]
# Lots of omitted output...
[Loaded kuporific.Main from file:/tmp/build/classes/main/]
        ^ here!
[Loaded sun.launcher.LauncherHelper$FXHelper from /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Class$MethodArray from /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded kuporific.A from file:/tmp/build/classes/main/]
        ^ here!
[Loaded java.lang.Shutdown from /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Shutdown$Lock from /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/jre/lib/rt.jar]

BUILD SUCCESSFUL

Total time: 6.502 secs

We can see when kuporific.Main and kuporific.A were loaded, and we do not see either kuporific.A$B or kuporific.A$C being loaded.

Community
  • 1
  • 1
kuporific
  • 10,053
  • 3
  • 42
  • 46
  • Not exactly. `A.class` still retains information that `A$B` is an inner class of `A`. You can access this information via reflection. – ghik Nov 24 '14 at 13:15
  • @ghik True enough, but loading class `A` will not load the inner class `B`, static or not. I have edited my answer to better explain this. – kuporific Nov 24 '14 at 18:12
  • @ghik The compiler performs some subtle magic to make the semantics of inner classes work (which is part of your "not exactly".) – kuporific Nov 24 '14 at 18:20
  • But calling getEnclosingClass() A$B will nevertheless load A. So this information must be somewhere. Is it in the name? –  Sep 20 '17 at 23:46
  • Could you please also provide official documentation for the same if any? – Arun May 31 '20 at 14:59
3

Inner classes i.e class B cannot exist outside the parent class. You need to construct the parent class i.e class A first.

and if you remove static from your inner class i.e for non-static inner class , you need to pass the parent class in during construction of the inner class.

Object a = Class.forName("A").newInstance();    //object of outer class

//object of inner class
Object b = implClass.getDeclaredConstructor(new Class[] { a.getClass() })
        .newInstance(new Object[] { a });
rachana
  • 3,344
  • 7
  • 30
  • 49
  • 1
    I don't think that is true for **static** inner classes – dkatzel Jul 02 '14 at 19:03
  • @ dkatzel This solution is mainly for non static inner classes and he question is for bolth `satic inner classes` and `nonstatic inner classes` – rachana Jul 02 '14 at 19:09
  • OK I see that now, if you make your answer more clear that the code is for non-static only. I will remove down vote. (maybe add reflection call for how to call static inner class ?) – dkatzel Jul 02 '14 at 19:14
2

A ClassLoader will not load a class, unless it was requested (e.g. using loadClass). While loading a class, a ClassLoader will request referenced classes.

As your class A does not reference A.B, A.B will not be loaded, whether it is static or not. (To be honest, A does reference A.B, but not in a manner causing the ClassLoader to load A.B.)

If you add a field of type A.B or use the type A.B in another way (e.g. as a method return type), it will actually be referenced in A.class and therefore be loaded.

Tobias
  • 7,723
  • 1
  • 27
  • 44
2

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.

Almir Campos
  • 2,833
  • 1
  • 30
  • 26
0

No, the nested class will not be loaded, in either case.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724