把java的po的值赋值到另一个相同的po中
时间: 2024-03-21 22:43:47 浏览: 12
如果您想将一个Java对象的属性值赋值给另一个相同类型的Java对象,可以使用Java的反射机制来实现。以下是一个示例代码:
```java
public static void copyProperties(Object source, Object target) throws IllegalAccessException, InvocationTargetException {
Class<?> sourceClass = source.getClass();
Class<?> targetClass = target.getClass();
// 获取源对象和目标对象的所有属性
Field[] sourceFields = sourceClass.getDeclaredFields();
Field[] targetFields = targetClass.getDeclaredFields();
for (Field sourceField : sourceFields) {
// 遍历源对象的属性
sourceField.setAccessible(true);
Object sourceValue = sourceField.get(source);
for (Field targetField : targetFields) {
// 遍历目标对象的属性
targetField.setAccessible(true);
if (sourceField.getName().equals(targetField.getName())) {
// 如果属性名称相同,则将源对象的属性值赋值给目标对象
targetField.set(target, sourceValue);
break;
}
}
}
}
```
使用示例:
```java
public class Person {
private String name;
private int age;
// 省略 getter 和 setter 方法
}
Person source = new Person();
source.setName("Tom");
source.setAge(20);
Person target = new Person();
copyProperties(source, target);
System.out.println(target.getName()); // 输出 "Tom"
System.out.println(target.getAge()); // 输出 "20"
```
请注意,该代码示例仅考虑了两个对象的属性名称相同的情况。如果属性名称不同,或者属性类型不同,需要进行更多的判断和转换。