- 编辑 - 这里我给出了一个特定的对象。作为一个例子,但我要求任何 obj.我被给予*
我正在寻找一种方法来获取类和对象的所有子类中的所有公共(public)属性(属性的名称及其值)。 假设我们有一个 People 对象:
i
mport 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;
}
}
}
}
我在这里看到了一个引用(我不能在那里发表评论,因为我没有足够的积分): Java reflection get sub class variable values / get object instance from member field
并尝试实现它,但我的输出是
ppl [People$Person@4aa298b7, People$Person@7d4991ad]
而我需要它需要进入每个人并提取其变量(及其值)。我搜索了可以帮助我的信息,但找不到任何内容......有什么建议吗?
最佳答案
public People() {
ppl.add(new Person(55, "Daddy", "Long Legs"));
ppl.add(new Person(20, "Jhon", "Snow"));
for (Person person : ppl) {
System.out.println(person.name.last);
System.out.println(person.name.first);
System.out.println(person.age);
}
System.out.println("Size of list: " + ppl.size());
}
没有 toString() 方法的示例。
关于java - 获取Java中所有公共(public)变量的名称和值(包括继承对象的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48765082/