反射获取类的 属性名(name) 和值(value)

1.新建对象user:

package com.entity;

public class User {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }
    
}
2 .  * 获取类中写  属性名 数组

    /**
     * * 获取属性名数组
     * 
     * @param person
     * @return
     */
    public static String[] getFiledName(User user) {

        Field[] fields = user.getClass().getDeclaredFields();
        String[] fieldNamStrings = new String[fields.length];
        for (int i = 0; i < fieldNamStrings.length; i++) {
            fieldNamStrings[i] = fields[i].getName();

        }

        return fieldNamStrings;

    }

3.  * 根据 类中的 属性名字 获取值 (value)

/**
     * 
     * @Description 根据属性名 获取值(value)
     * @param name
     * @param user
     * @return
     * @throws IllegalAccessException
     */
    public static Object getFieldValueByName(String name, User user) throws IllegalAccessException {

        String firstletter = name.substring(0, 1).toUpperCase();

        String getter = "get" + firstletter + name.substring(1);

        Method method;
        Object value;
        try {
            method = user.getClass().getMethod(getter, new Class[] {});

            value = method.invoke(user, new User[] {});

            return value;
        } catch (NoSuchMethodException e) {

            e.printStackTrace();
        } catch (SecurityException e) {

            e.printStackTrace();
        } catch (IllegalArgumentException e) {

        } catch (InvocationTargetException e) {

            e.printStackTrace();
        }
        return null;
    }

4.  编写 测试方法

public static void main(String[] args) {
         User user = new     User();
         user.setName("zhangsan");
         user.setId("1");
        
        String[] fieldNames = getFiledName(user);
        for (int j = 0; j < fieldNames.length; j++) { // 遍历所有属性
            String name = fieldNames[j]; // 获取属性的名字
            Object value;
            try {
                value = getFieldValueByName(name, user);
             // 根据属性获取value值
            // 加载裁决书模块设置实体类
            System.out.println("key="+name);
            System.out.println("value="+value);
            } catch (IllegalAccessException e) {
                
                e.printStackTrace();
            }
        }

    }

5. 运行结果 :

key=id
value=1
key=name
value=zhangsan
--------------------------------------------------------------------------------------------------------------------------------------------------------

       生活赋予我们一种巨大的和无限高贵的礼品,这就是青春:充满着力量,充满着期待志愿,充满着求知和斗争的志向,充满着希望信心和青春。 —— 奥斯特洛夫斯基

猜你喜欢

转载自blog.csdn.net/qq_38097573/article/details/81365111