Home > Java > javaTutorial > body text

Java reflection to get object content

(*-*)浩
Release: 2019-10-14 16:29:39
forward
2578 people have browsed it

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));
    }
       
}
Copy after login

Test Bean

@Data
public class Bean{
private String userName;
private String userId;
private String userPwd;
private String userPhone;
}
Copy after login

Call

public static void main(String[] args){
 
    Bean bean = new Bean();
    bean.setUserName("张大炮");
    bean.setUserId("zdp2000");
    bean.setUserPwd("zhangdapaopwd123");
    bean.setUserPhone("18666886688");
 
    test(bean);
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template