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;
}
}
把list<object> list 指定属性进行拼接
最新推荐文章于 2023-12-22 10:44:33 发布