Instantiate nested static class using Class.forName

JavaStatic

Java Problem Overview


I have a nested static class like:

package a.b
public class TopClass {

    public static class InnerClass {
    }
}

I want to instantiate with Class.forName() but it raises a ClassNotFoundException .

Class.forName("a.b.TopClass"); // Works fine.
Class.forName("a.b.TopClass.InnerClass"); // raises exception

TopClass.InnerClass instance = new TopClass.InnerClass(); // works fine

What is wrong in my code?

Udo.

Java Solutions


Solution 1 - Java

Nested classes use "$" as the separator:

Class.forName("a.b.TopClass$InnerClass");

That way the JRE can use dots to determine packages, without worrying about nested classes. You'll spot this if you look at the generated class file, which will be TopClass$InnerClass.class.

(EDIT: Apologies for the original inaccuracy. Head was stuck in .NET land until I thought about the filenames...)

Solution 2 - Java

try

Class.forName("a.b.TopClass$InnerClass");

Solution 3 - Java

Inner classes are accessed via dollar sign:

Class.forName("a.b.TopClass"); 
Class.forName("a.b.TopClass$InnerClass"); 

Solution 4 - Java

Inner class is always accessed via dollar sign because when java compiler compile the java source code file it generates .class file(byte code).

if there is only one class for example Hello.java and this class is an outer class then java compiler on compilation generate Hello.class file but if this class has an inner class HelloInner then java compiler generates d Hello$HelloInner.class(byte code).

so bytecode always looks like for following snippet with name Outer.java:

   public class   Outer
   {
     public  var;//member variable
       Outer()//constructor
       {
        }
       class  Inner1
        {
          class Inner2
             {  
              }
         }
       }

so byte code is:Outer$Inner1$Inner2.class

that's why we use $ sign to access inner class .:)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionssedanoView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaSilfverstromView Answer on Stackoverflow
Solution 3 - JavaArt LicisView Answer on Stackoverflow
Solution 4 - JavaSumit JhajhariaView Answer on Stackoverflow