How to instantiate if inner class with getConstructor ()

Possible duplicate:
Java: How do I load a class (and its inner classes) that is already on the class path?

Can someone help me understand how to instantiate an inner class using getConstructor.

That's where I am now.

import java.lang.reflect.*;

public class Outer{
public Outer(int i){
//things to do
}
public class Inner{
Class<?>[] type = new Class<?>[1];
Class<?> myClass;
    public Inner(int i){
    //stuff and code
    }

    public void task(){
    type[0] = Integer.class;
    try{
        myClass = Class.forName("Outer$Inner");
        Constructor construct = myClass.getConstructor(type);
        Object i = construct.newInstance(new Integer(43));
    }
    catch(Exception e){
        e.printStackTrace();
    }
    }
}

public static void main(String[] args){
Outer outer = new Outer(new Integer(21));
Inner inner = outer.new Inner(new Integer(22));
inner.task();
}

}

error information

java.lang.NoSuchMethodException: Outer$Inner.<init>(java.lang.Integer)
at java.lang.Class.getConstructor0(Class.java:2706)
at java.lang.Class.getConstructor(Class.java:1657)
at Outer$Inner.task(Outer.java:18)
at Outer.main(Outer.java:30)

Sorry if I am missing something obvious. If I can understand this, I would like to get the input from the txt file and use the string to create the objects.

+3
source share
1 answer

Does it work if you change the InnerClass instead of the static class?

Outer , . , - :

http://jroller.com/tomdz/entry/reflection_inner_classes

+5

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


All Articles