开发者

How to create an instance if a inner class with getConstructor() [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

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

Could someone help me understand how to create an instance of an inner class using getConstructor.

Here is where开发者_开发问答 I am at right 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 figure this out I would like to take input from a txt file and use the string to create objects.


Does it work if you change InnerClass to be a static class instead?

It generally needs the context of the Outer class to create the inner class, if it's not a static inner class. I believe you need to pass the Outer instance to the constructor - let me pull a random reference out my rear:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜