mardi 13 février 2018

Get all public variables names & values (including of inherited object) in Java

I'm looking for a way to get all public attributes in the class and all subclasses of an object (name of the attribute and its value). Let say there People object:

import java.util.ArrayList;

public class People {
    public ArrayList<Person> ppl= new ArrayList<Person>();
    int count=2;
    public People() {
        ppl.add(new Person(55, "Daddy", "Long Legs"));
        ppl.add(new Person(20, "Jhon", "Snow"));
    }
    public class Person{
        public int age;
        public Name name;
        public Person(int age, String first, String last){
            this.name = new Name(first, last);
            this.age = age;
        }
        public class Name{
            String first;
            String last;
            public Name(String first, String last) {
                this.first = first;
                this.last = last;
            }
        }
    }

}

I saw a reference here (I can't comment on there bc I don't have enough points): Java reflection get sub class variable values / get object instance from member field

and tried to implement it also but then my output is

ppl [People$Person@4aa298b7, People$Person@7d4991ad]

whereas I need it needs to go into each Person and extract its variables(and their values). In addition theattribute count doesn't appear there. I searched for a information that could help me but I couldn't find anything..any advice?





Aucun commentaire:

Enregistrer un commentaire