dimanche 18 juillet 2021

calling a class implementing an interface using reflections

I'm using reflections to find all classes implementing IAnimal Interface. but how do I call or return a class using the animals set in the below code:

Reflections reflections = new Reflections(IAnimal.class);    
Set<Class<? extends IAnimal>> animals= reflections.getSubTypesOf(IAnimal.class);

I have 3 classes implementing IAnimal interface Dog, Cat, Duck. and I want to apply this logic but I don't know how to do it.

    method findAnimal(String animalName){

        for (Iterator<Class<? extends Operations>> it = animals.iterator(); it.hasNext(); ) {
            String classname=it.Name;
            if (classname.eqauls(animalName)){
               System.out.println("found");
                return new class(); }
        }}

I want the findAnimal method to return a class instance if matched with the passed string. i.e., if I passed a "Dog" string as a parameter, the method will return a dog class.

is it possible to do that, any ideas on how to implement the logic in the box above?





Aucun commentaire:

Enregistrer un commentaire