用Java反射输出对象的所有属性的值

获取对象的类类型

Class cls = obj.getClass();

用类类型获取属性数组

getFields()获取的是共有属性
getDeclaredFields()可以获取所有属性
Field[] fields = cls.getDeclaredFields();

遍历属性数组,将属性设置为外部可见,然后输出

       for (Field field:fields) {
            field.setAccessible(true);
            try {
                System.out.println(field.getName()+":"+field.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

完整代码:

PrintAllFields.java

import java.lang.reflect.Field;

public class PrintAllFields {
    public static void printAllFields(Object obj){
        Class    cls=obj.getClass();
        Field[] fields=cls.getDeclaredFields();
        System.out.println("共有"+fields.length+"个属性");
        for (Field field:fields) {
            field.setAccessible(true);
            try {
                System.out.println(field.getName()+":"+field.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Student student=new Student();
        student.setId(2014222);
        student.setName("李利");
        student.setAge(22);
        student.setSex(1);
        student.setGrade(3);
        PrintAllFields.printAllFields(student);
    }
}

Student.java


public class Student {
    private int id;
    private String name;
    private int age;
    private int grade;
    private int sex;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getGrade() {
        return grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }
}
posted @ 2017-05-29 22:59  渐入佳境coder  阅读(3369)  评论(0编辑  收藏  举报