通过Java反射获得对象里面的所有字段名以及字段对应的值
public static void test(Bean bean) {
Field[] fields = bean.getClass().getDeclaredFields();
for(Field field :fields) {
//设置是否允许访问,不是修改原来的访问权限修饰词。
field.setAccessible(true);
//获取字段名,和字段的值
System.out.println("name: "+field.getName() + "value: " +field.get(bean));
}
}
测试Bean
@Data
public class Bean{
private String userName;
private String userId;
private String userPwd;
private String userPhone;
}
调用
public static void main(String[] args){
Bean bean = new Bean();
bean.setUserName("张大炮");
bean.setUserId("zdp2000");
bean.setUserPwd("zhangdapaopwd123");
bean.setUserPhone("18666886688");
test(bean);
}