Java - 如何用反射实例化内部类?

时间:2015-10-27 07:06:42

标签: java android reflection

我一直遇到使用反射实例化内部类的问题。这是一个例子。

public final class Cow {

    public Cow (Bufallo flying, Horse swimming, int cowID, int numCows) {
        //This is where the part I really dont know what the cow is doing
    }

    public Bull eatGrass(String grassName, AngusCattle farmName, JerseyCattle farmName){
        Ox newBreed = new Ox(australiaFarm, somewhereOutThere);
        //Something that has to do with cow eating grass
        return Bull;
    }

    private static final class Ox extends BigHorns {

        public Ox (AngusCattle farmName, ChianinaOx farmName) {
            //Something about mating
        }

    }

}

我想要的只是获取构造函数或者只是实例化内部类。我的代码到目前为止......

CowManager cowManager = (CowManager) this.getSystemService(Context.COW_SERVICE);
final Class MainCowClass  = Class.forName(cowManager.getClass().getName());
final Class[] howManyCows = MainCowClass.getDeclaredClasses();
Class getCow = null;
for (int i=0; i < howManyCows.length; i++) {
    if (! howManyCows[i].getName().equals("Cow$Ox")) {
        continue;
    }
    getCow = Class.forName(howManyCows[i].getName());
}
Constructor createCow = getCow.getDeclaredConstructor();

到目前为止,我似乎无法在牛身上找到牛的构造者

1 个答案:

答案 0 :(得分:0)

您需要首先通过执行以下操作来访问内部类

// Straightforward parent class initializing
Class<?> cowClass = Class.forName("com.sample.Cow");
Object cowClassInstance = cowClass.newInstance();

// attempt to find the inner class
Class<?> oxClass = Class.forName("com.sample.Cow$Ox");

// Now find the instance of the inner class, you may need to pass in arguments for the constructor
Constructor<?> oxClassContructor = oxClass.getDeclaredConstructor(cowClass);

// initialize the inner instance using the parent class's (cow's) instance
Object oxClassInstance = oxClassContructor.newInstance(cowClassInstance);

修改

构造函数应如下所示

// define the type of args that the constructor requires.
oxClass.getDeclaredConstructor(com.sample.AngusCattle.class, com.sample.ChianinaOx.class);
// now init the constructor with the required args.
Object oxClassInstance = oxClassContructor.newInstance(cowClassInstance, angusCattleClassInstance, chianinaOxClassInstance);