Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Inner classes can indeed not be constructed without constructing the parent class first. It cannot exist outside the parent class. You'll have to pass an instance of the parent class in when doing reflection. Nested classes are <code>static</code> and they can be used independently from the parent class, thus also when doing reflection.</p> <p>Here's an <a href="http://sscce.org" rel="noreferrer">SSCCE</a> which demonstrates all the stuff. </p> <pre><code>package mypackage; import java.lang.reflect.Modifier; public class Parent { public static class Nested { public Nested() { System.out.println("Nested constructed"); } } public class Inner { public Inner() { System.out.println("Inner constructed"); } } public static void main(String... args) throws Exception { // Construct nested class the normal way: Nested nested = new Nested(); // Construct inner class the normal way: Inner inner = new Parent().new Inner(); // Construct nested class by reflection: Class.forName("mypackage.Parent$Nested").newInstance(); // Construct inner class by reflection: Object parent = Class.forName("mypackage.Parent").newInstance(); for (Class&lt;?&gt; cls : parent.getClass().getDeclaredClasses()) { if (!Modifier.isStatic(cls.getModifiers())) { // This is an inner class. Pass the parent class in. cls.getDeclaredConstructor(new Class[] { parent.getClass() }).newInstance(new Object[] { parent }); } else { // This is a nested class. You can also use it here as follows: cls.getDeclaredConstructor(new Class[] {}).newInstance(new Object[] {}); } } } } </code></pre> <p>This should produce</p> <pre> Nested constructed Inner constructed Nested constructed Inner constructed Nested constructed </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload