I am working on an instance creation method that will allow me to pack many similar classes into one external class. Then I could instantiate each unique type of the class by passing it to the constructor. After many research and mistakes, this is what I came up with. I left a mistake to demonstrate my question.
import java.lang.reflect.Constructor; public class NewTest { public static void main(String[] args) { try { Class toRun = Class.forName("NewTest$" + args[0]); toRun.getConstructor().newInstance(); } catch(Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); } } public NewTest(){} private class one //Does not instantiate { public one() { System.out.println("Test1"); } } private static class two //Instantiates okay { public two() { System.out.println("Test2"); } } }
Compiling this code and running java NewTest two leads to the conclusion of Test2 , as I expected.
Running java NewTest one results in
java.lang.NoSuchMethodException: NewTest$one.<init>() at java.lang.Class.getConstructor(Unknown Source) at java.lang.Class.getConstructor(Unknown Source) at NewTest.main(NewTest.java:12)
I got confused about this because, as far as I know, I am right about the inner class, the outer class must have access to the inner class, and I have a default arg constructor.
source share