简体   繁体   中英

Java - How to instantiate inner class with reflection?

I have been having problems with the instantiating the inner class using reflection. Heres an example.

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
        }

    }

}

all I want is to get the constructor or just instantiate the inner class. My code so far...

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();

as of the moment I cant seem to find the constructor of ox inside the cow

You need to first access the inner class by doing something like below

// 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);

Edit

The constructors should look like below

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM