Java: How to load a class (and its inner classes) that is already on the way to the class?

How can I load a class that is already on the class path, an instance of it, and also instantiate any inner classes defined in it?

EG:

public class TestClass { public class InnerClass { } } 
+6
java reflection classloader
source share
3 answers

Inner classes cannot exist outside the parent class. First you need to create a parent class. Without reflection, it would look like this:

 InnerClass innerClass = new TestClass().new InnerClass(); 

In reflection, you need to pass the parent class during the construction of the inner class.

 Object testClass = Class.forName("com.example.TestClass").newInstance(); for (Class<?> cls : testClass.getClass().getDeclaredClasses()) { // You would like to exclude static nested classes // since they require another approach. if (!Modifier.isStatic(cls.getModifiers())) { Object innerClass = cls .getDeclaredConstructor(new Class[] { testClass.getClass() }) .newInstance(new Object[] { testClass }); } } 
+14
source share

As a side note, given that your main question has been answered - often people will declare inner classes, as in your example above, without thinking about whether they can be static inner classes.

In my experience, the vast majority of (non-anonymous) inner classes can be static because they do not need to access members of an instance of their parent class. Declaring the inner class as static in this case is more efficient (since the runtime does not require defining a new class for each parent instance), it is less confusing (with new TestClass().new InnerClass().getClass() != new TestClass().new InnerClass().getClass() ) and it is easier to create if you do not have a suitable instance of TestClass .

So, if this applies to you, you can (and perhaps should) declare you an inner class:

 public class TestClass { public static class InnerClass { } } 

and then you can just create it as new TestClass.InnerClass() .

(If you need to access member fields from InnerClass, then just ignore it all!)

+6
source share

Class.forName ("your class name"). newInstance ().

Inner classes will only be created if the constructor creates them.

+1
source share

All Articles