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.
forName. Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName ) this method attempts to locate, load, and link the class or interface.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass. InnerClass innerObject = outerObject.
A static inner class can be instantiated without the need for an instance of the outer class. In general, an Inner class is a part of nested class, called Non-static nested classes in Java. The types of inner classes are member inner class, anonymous inner class, and local inner class.
Inner or Nested classes are not the most commonly used feature in Python. But, it can be a good feature to implement code. The code is straightforward to organize when you use the inner or nested classes.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With