lundi 28 octobre 2019

How to use reflection with multiple classes extending the base class in java

I am very new to reflections and I would like to get some advices/help. I am trying to get the subclass names using reflection in the base class. I have multiple subclasses (Cat, Dog, Frog etc..) and all of them extend the base class (Animal).

What I want to do is getting the class names from the subclasses themselves and pass them through the constructors so the Animal does not have to instantiate dozens of subclasses. Below is an example of what I am NOT trying to do.

If there is a way to just dynamically get the subclasses names without going through the pain of instantiating every single subclass, I would love to see it. Your help is much appreciated.

class Dog extends Animal 
{ 
    private String s; 

    public Dog() {
            s = "Bark";  } 


    public void method() { 
        System.out.println("Dogs " + s); 
    } 
}
class Cat extends Animal 
{ 
    private String s; 

    public Cat() {
            s = "Meow";  } 


    public void method() { 
        System.out.println("Cats " + s); 
    } 
}

class Animal 
{
 public static void main(String args[]) throws Exception 
 { 

        Dog dog = new Dog(); 
        Cat cat = new Cat(); 

        Class cls = dog.getClass(); 
        System.out.println("The name of class is " + 
                            cls.getName()); 

        Constructor constructor = cls.getConstructor(); 
        System.out.println("The name of constructor is " + 
                            constructor.getName()); 

}




Aucun commentaire:

Enregistrer un commentaire