Get all the field names in the object and the corresponding values of the fields through Java reflection
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)); } }
Test Bean
@Data public class Bean{ private String userName; private String userId; private String userPwd; private String userPhone; }
Call
public static void main(String[] args){ Bean bean = new Bean(); bean.setUserName("张大炮"); bean.setUserId("zdp2000"); bean.setUserPwd("zhangdapaopwd123"); bean.setUserPhone("18666886688"); test(bean); }
The above is the detailed content of Java reflection to get object content. For more information, please follow other related articles on the PHP Chinese website!