Search code examples
javaabstractreflect

Get parameter value using 'Reflect'


I'm still playing with Java and I've not experience.... Ok, my question is: is it possible to get, dynamically, the value of fields of a class ? Here with an example: The 'My_Zoo' is my class, which can have different fields 'animal', ie. dog1, dog2, chitchen1,...

But I want to get their value (i.e. common field 'Number_of_arms') dynamically.

So, for the class My_Zoo I have only one Field variable and from It I want to get the value 'Number_of_arms'.

The reason why I'm using abstract class is that I home to say to the system: 'the Field field is an 'animal' type then give me the value of parameter 'Number_of_arms''

Is it possible ?

    public class My_Zoo{

        public abstract class Animal{
            String name;
            String color;
            int Number_of_arms;
            public String getName(){
                return name;
            }
            public int getNumber_of_arms(){
                return Number_of_arms;
            }            
        }

        public class Dog extends Animal{
            public Dog(String name, String color){
                this.name = name;
                this.color = color;
                this.Number_of_arms = 4;
            }
        }

        public class Chicken extends Animal{
            public Chicken(String name, String color){
                this.name = name;
                this.color = color;
                this.Number_of_arms = 2;
            }        
        }

        Dog dog_Charlie = new Dog("Charlie", "black");
        Dog dog_Bobo = new Dog("Bobo", "brawn");
        Chicken chicken_Princess = new Chicken("Princess", "brawn"); 

        public My_Zoo(){
            Field[] fields = this.getClass().getDeclaredFields();
            int Number_of_arms;

            for (Field field: fields){
                ??? Number_of_arms = field...Number_of_arms ???
            }
        }
    }

In the code, the row ??? Number_of_arms = field...Number_of_arms ??? is missing. What I have to use?

Thank you


Solution

  • Hope it will help you:

    for (Field field : fields) {
        Animal temp = (Animal) field.get(this);
            System.out.println(temp.getName() + ": " + temp.getNumber_of_arms());
        }
    }