1、创建一个student的对象:
public class Student { private Integer id; private String name; private String sex; private String phone; public Student() { } public Student(Integer id, String name, String sex, String phone) { this.id = id; this.name = name; this.sex = sex; this.phone = phone; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
2、利用反射获取student对象的字段名,类型,值:
public class UseReflexGetPOJOInfo { public static void main(String[] args) throws IllegalAccessException { Student student = new Student(); student.setId(1); student.setName("张三"); student.setSex("男"); student.setPhone("13267356***"); Integer id = student.getId(); Field[] declaredFields = student.getClass().getDeclaredFields(); for (Field declaredField : declaredFields) { //允许访问私有属性,此步骤需要,不然无法获取值(因为Student对象的字段用privae修饰) declaredField.setAccessible(true); String name = declaredField.getName(); Class<?> type = declaredField.getType(); //截取类型 String str = String.valueOf(type); String substring = str.substring(str.lastIndexOf(".")+1); //获取值 Object value = declaredField.get(student); } } }