java遍历实体类的属性和值

代码如下:

实体类:

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private String pkid;
    
    private String userName;
    
    private String passWord;
    
    private String roleID;
}

遍历:

public class test {

        public static void main(String[] args) throws Exception{  
            User e = new User();  
            reflect(e);  
        }
        
        public static void reflect(User e) throws Exception{  
            Class cls = e.getClass();  
            Field[] fields = cls.getDeclaredFields();  
            for(int i=0; i<fields.length; i++){  
                Field f = fields[i];  
                f.setAccessible(true);  
                System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(e));  
            }   
        } 
}

输出:

原文地址:https://www.cnblogs.com/ynxrsoft/p/7444453.html