Home >Java >javaTutorial >Java reflection to get object content

Java reflection to get object content

(*-*)浩
(*-*)浩forward
2019-10-14 16:29:392651browse

Java reflection to get object content

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete