java反射動態獲取對象和塞入對應的值

/**
     * 爲指定對象的指定屬性動態賦予指定值
     *
     * @param obj       指定對象
     * @param fieldName 指定屬性
     * @param value     指定值
     * @return obj      返回對象
     */
    public static Object dynamicSetValue(Object obj, String fieldName, Object value) {
        try {
            // 取屬性首字母轉大寫
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            // set方法名
            String setMethodName = "set" + firstLetter + fieldName.substring(1);
            // 獲取屬性
            Field field = obj.getClass().getDeclaredField(fieldName);
            // 獲取set方法
            Method setMethod = obj.getClass().getDeclaredMethod(setMethodName, field.getType());
            // 通過set方法動態賦值
            setMethod.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 動態獲取指定對象指定屬性的值
     *
     * @param obj       指定對象
     * @param fieldName 指定屬性
     * @return 屬性值
     */
    public static Object dynamicGetValue(Object obj, String fieldName) {
        try {
            // 取屬性首字母轉大寫
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            // get方法名
            String getMethodName = "get" + firstLetter + fieldName.substring(1);
            // 獲取get方法
            Method getMethod = obj.getClass().getDeclaredMethod(getMethodName);
            // 動態取值
            return getMethod.invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章