I'm using reflections to find all classes implementing IAnimal Interface. but how do I return a class instance 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?
So this basically boils down to how to create an instance having the java.lang.Class
that represents that type?
You can create an instance by using the following code:
Class<?> cl = it.next();
... if condition, you decide to create the instance of cl
IDog object= cl.getDeclaredConstructor().newInstance(); // will actuall be a Dog, Cat or whatever you've decided to create
Note, you've assumed that the default constructor exists (the constructor without arguments). This kind of assumption is necessary, because you have to know how to create the object of the class of your interest.
If you know, that you have constructor that takes some specific parameters (of specific types) you can pass the parameter types to the getDeclaredConstructor
method. For example, for class Integer
that has a constructor with one int
argument the following will print "5":
Integer i = Integer.class.getDeclaredConstructor(int.class).newInstance(5);
System.out.println(i);