通过反射给有固定字符串的属性字段的实体赋值

一、需求

项目中有时候需要返回属性累加结构的数据,例如:

[{
        "column0": "d80f37d3-7ba8-4c10-b511-d1a12ddef723",
        "column1": "d8e09b51-5c0d-44f0-96c6-89c8ab5fc975",
        "column2": "9547f653-18e1-45ec-9cd2-a9b968a98832",
        "column3": "102a9f3b-a33e-4007-a734-f21e0eb80a50",
        "column4": "061af790-ef58-49fe-85b4-2fc99b23a64c"
    },
    {
        "column0": "2662b0c1-732c-4830-8bdd-4fa3f6dcb76a",
        "column1": "998907b4-b92f-4548-b6f4-22b45855b29f",
        "column2": "4e92623b-9753-4fd7-8c78-3777920dd8a6",
        "column3": "99c9b9eb-91db-4efb-93d5-a7e523cdca88",
        "column4": "d2eb07f2-c0f3-4ea6-b700-2eaa2e48d114"
    },
    {
        "column0": "4f79bf59-5f32-4fbd-9249-c23debeede25",
        "column1": "912963eb-3b49-480d-98e6-e8df8a191a6f",
        "column2": "7c368d07-459c-4304-8666-d2b906ad9f56",
        "column3": "2a0b0777-a031-4b05-812d-c56bc6285cd8",
        "column4": "6d40c26d-58dc-445a-93e8-0ceab49e121d"
    }
]

或者

{
    "column0": "3973b4ba-b9eb-43de-8f56-34943dab3802",
    "column1": "e559748d-f66c-45a8-80fc-048ef452c630",
    "column2": "045a3e88-6e0d-4898-8410-46d5bc06acd7",
    "column3": "a2ebdd30-f741-4738-81de-5fe3cfe86482",
    "column4": "061e27f8-3d1d-4a3b-b7d4-00ba04674f9d"
}

二、定义实体类

import lombok.Data;

/**
 * @Author:
 * @Description
 * @Date: 下午3:47 2024/1/22
 */
@Data
public class SysEntity {

    private String column0;
    private String column1;
    private String column2;
    private String column3;
    private String column4;

}

三、定义测试类

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author:
 * @Description
 * @Date: 下午3:48 2024/1/22
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestFieldController {

    @GetMapping("/field")
    public String test() {
        SysEntity entity = new SysEntity();
        for (int i = 0; i < 10; i++) {
            setEntityField(entity, i, UUID.randomUUID().toString());
        }
        return JSONObject.toJSONString(entity);
    }

    @GetMapping("/list")
    public String testList() {
        List<SysEntity> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            SysEntity entity = new SysEntity();
            Boolean aBoolean = setEntityField(entity, i, UUID.randomUUID().toString());
            //判断属性是否存在
            if (aBoolean) {
                list.add(entity);
            }
        }
        return JSONArray.toJSONString(list);
    }

    /**
     * 给对应的属性赋值
     *
     * @param entity
     * @param index
     * @param value
     * @return
     */
    public static Boolean setEntityField(SysEntity entity, int index, String value) {
        boolean flag = false;
        String methodName = "";
        try {
            //手动设置set方法名
            methodName = "setColumn" + index;
            Method method = entity.getClass().getMethod(methodName, String.class);
            // 调用对应的方法设置属性值
            method.invoke(entity, value);
            flag = true;
//        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        } catch (Exception e) {
            // 处理异常 根据实际业务场景,判断是否需要捕获异常.这里我只打印了日志
            log.error("实体属性不存在 methodName={}", methodName);
        }
        return flag;
    }

}

四、测试

1、浏览器输入:http://localhost:8876/test/list

2、浏览器输入:http://localhost:8876/test/field