java ab两个对象,把b对象中与a对象中相同的字段的值复制到a对象中,比如a对象中有name="张三,age=18,b对象中有name=“李四,adress=“南京”,name是一样的,所以把a对象中的张三改成李四
时间: 2024-03-21 13:38:41 浏览: 57
可以使用反射实现该操作,以下是示例代码:
```java
import java.lang.reflect.Field;
public class ObjectUtil {
public static void copySameFields(Object a, Object b) {
Class<?> clazzA = a.getClass();
Class<?> clazzB = b.getClass();
Field[] fieldsA = clazzA.getDeclaredFields();
Field[] fieldsB = clazzB.getDeclaredFields();
for (Field fieldA : fieldsA) {
for (Field fieldB : fieldsB) {
if (fieldA.getName().equals(fieldB.getName())
&& fieldA.getType().equals(fieldB.getType())) {
fieldA.setAccessible(true);
fieldB.setAccessible(true);
try {
Object valueB = fieldB.get(b);
fieldA.set(a, valueB);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
```
使用方法如下:
```java
public static void main(String[] args) {
A a = new A("张三", 18);
B b = new B("李四", "南京");
ObjectUtil.copySameFields(a, b);
System.out.println(a.getName()); // 输出"李四"
}
```
其中,A类和B类分别如下:
```java
public class A {
private String name;
private int age;
public A(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class B {
private String name;
private String address;
public B(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
```
阅读全文