Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate nested static class using Class.forName

Tags:

java

static

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.

like image 815
ssedano Avatar asked Aug 10 '11 08:08

ssedano


People also ask

What is the use of class forName ()?

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.

How do you initialize a nested class?

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.

Can you instantiate a static class?

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.

Can you nest classes in Python?

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.


1 Answers

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

like image 105
Jon Skeet Avatar answered Oct 08 '22 20:10

Jon Skeet