Java遍历对象的属性和值

在Java类中,我们可以使用反射中的getDeclaredFields()或者getFields()方法来获取属性和值。

  • getFields():获取某个类的所有的public字段,其中是包括父类的public字段的。
  • getDeclaredFields():获取某个类的自身的所有字段,不包括父类的字段。
  • 比如测试类:

    public class Test {
        public int id;
        public String name;
    

    获取类的属性和值

    public class Application {
        public static void main(String[] args) throws Exception {
            Test test = new Test();
            test.id = 1;
            test.name = "guoke";
            // 遍历输出属性
            Field[] fields =  test.getClass().getDeclaredFields();
            for( int i = 0; i < fields.length; i++){
                Field f = fields[i];
                System.out.println("属性名:"+f.getName()+",属性值:"+f.get(test));
    

    设置类的属性值,比如做一个类成员属性深拷贝

    public class Test {
        public int id;
        public String name;
        public void copy(Test obj){
            try {
                Field[] fields =  obj.getClass().getDeclaredFields();
                for( int i = 0; i < fields.length; i++){
                    Field f = fields[i];
                    f.set(this, f.get(obj));
            } catch (Exception e) {
                Log.error(e);
    
    public class Application {
        public static void main(String[] args) throws Exception {
            Test test = new Test();
            test.id = 1;
            test.name = "guoke";