NewInstance () with inner classes

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.

+6
source share
3 answers

Non-static inner classes require the outer class to work fine. Thus, they don’t have a “really” default constructor, they always have some kind of hidden parameter in which they expect an instance of an external class.

I do not know why you want them all to be in the same class. If you do this so that it is only one file, put them in a package and in separate classes. Having fewer files does not improve your program.

If instead you need to share something, so the outer class will work as a kind of "region", you can still do this without using inner classes, but passing them some context.

If you really want to instantiate an inner class, you need to use a hidden constructor that takes an outer class as a parameter:

 NewTest outer = new NewTest(); Class<?> toRun = Class.forName("NewTest$" + args[0]); Constructor<?> ctor = toRun.getDeclaredConstructor(NewTest.class); ctor.newInstance(outer); 
+13
source

A non-static inner class cannot be created without an instance of its parent class.

 new NewTest().new one() 

The called call creates an instance of one successfully.

Your two is created without an external instance due to the static modifier. This is a static nested class .

See the difference between static nested classes and inner classes: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

+2
source

You need to make the static class one . Non-static nested classes must be instantiated by the containing class.

0
source

Source: https://habr.com/ru/post/974723/


All Articles