将两个Java对象合并为一个可以通过以下几种方式实现:
copyProperties(Object dest, Object orig)
,可以将源对象的属性值复制到目标对象中。这种方式适用于两个对象的属性名和类型完全相同的情况。import org.apache.commons.beanutils.BeanUtils;
public class MergeObjects {
public static void main(String[] args) {
SourceObject source = new SourceObject();
source.setName("John");
source.setAge(25);
DestinationObject destination = new DestinationObject();
destination.setAddress("123 Main St");
destination.setPhone("1234567890");
try {
BeanUtils.copyProperties(destination, source);
System.out.println(destination.getName()); // Output: John
System.out.println(destination.getAge()); // Output: 25
System.out.println(destination.getAddress()); // Output: 123 Main St
System.out.println(destination.getPhone()); // Output: 1234567890
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SourceObject {
private String name;
private int age;
// Getters and setters
}
class DestinationObject {
private String name;
private int age;
private String address;
private String phone;
// Getters and setters
}
public class MergeObjects {
public static void main(String[] args) {
SourceObject source = new SourceObject();
source.setName("John");
source.setAge(25);
DestinationObject destination = new DestinationObject();
destination.setAddress("123 Main St");
destination.setPhone("1234567890");
destination.setName(source.getName());
destination.setAge(source.getAge());
System.out.println(destination.getName()); // Output: John
System.out.println(destination.getAge()); // Output: 25
System.out.println(destination.getAddress()); // Output: 123 Main St
System.out.println(destination.getPhone()); // Output: 1234567890
}
}
class SourceObject {
private String name;
private int age;
// Getters and setters
}
class DestinationObject {
private String name;
private int age;
private String address;
private String phone;
// Getters and setters
}
以上两种方式都可以实现将两个Java对象合并为一个。具体选择哪种方式取决于对象的属性结构和合并需求。
没有搜到相关的结果
领取专属 10元无门槛券
手把手带您无忧上云