package com.test.test;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws IllegalAccessException {
Person p1 = new Person("张三", "高中生");
getObj(p1);
}
public static void getObj(Object obj) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
System.out.println(field.getName() + ":" + field.get(obj));
}
}
}
class Person {
private String name;
private String desc;
public Person(String name, String desc) {
this.name = name;
this.desc = desc;
}
public String getName() {
return name;
}
public Person setName(String name) {
this.name = name;
return this;
}
public String getDesc() {
return desc;
}
public Person setDesc(String desc) {
this.desc = desc;
return this;
}
}
输出结果
name:张三
desc:高中生