把list<object> list 指定属性进行拼接

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Object> objectList = new ArrayList<>();

        // 假设你有一些对象并将它们添加到列表中
        Object obj1 = new YourObject(25, "John", 1);
        Object obj2 = new YourObject(30, "Alice", 2);
        Object obj3 = new YourObject(22, "Bob", 3);
        objectList.add(obj1);
        objectList.add(obj2);
        objectList.add(obj3);

        String result = convertListToString(objectList, "id", "|");

        System.out.println(result);
    }

    public static String convertListToString(List<Object> objectList, String property, String separator) {
        StringBuilder result = new StringBuilder();
        result.append(property).append("=");

        for (Object obj : objectList) {
            if (obj instanceof YourObject) {
                YourObject yourObject = (YourObject) obj;
                // 使用反射根据属性名称获取属性值
                String value = getValueByPropertyName(yourObject, property);

                if (value != null) {
                    result.append(value).append(separator);
                }
            }
        }

        // 移除末尾多余的分隔符
        if (result.length() > property.length() + 1) {
            result.setLength(result.length() - separator.length());
        }

        return result.toString();
    }

    public static String getValueByPropertyName(YourObject object, String propertyName) {
        try {
            String methodName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
            // 使用反射获取指定属性的值
            return object.getClass().getMethod(methodName).invoke(object).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

class YourObject {
    private int age;
    private String name;
    private int id;

    public YourObject(int age, String name, int id) {
        this.age = age;
        this.name = name;
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值