我有一个叫OldClass的类,另一个叫NewClass的类。这两个类具有完全相同的字段。我可以将值从OldClass复制到NewClass,而无需手动调用每个类大约100个字段(200个此类对)的getter和setter。
答案 0 :(得分:1)
答案 1 :(得分:0)
只需序列化对象A并反序列化为ObjectB。
ObjectMapper mapper = new ObjectMapper();
String jsonResult = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(objectA);
TypeReference<ObjectB> typeRef
= new TypeReference<ObjectB>() {};
ObjectB objectB = mapper.readValue(jsonInput, typeRef);
答案 2 :(得分:0)
我建议使用Commons BeanUtils来完成此任务:
BeanUtils.copyProperties(destObj, srcObj);
要使其正常工作,两个对象都必须为Java Beans,这归结为具有遵循bean命名约定的getter和setter和无参数构造函数。
基本示例:
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsTest {
public static final class Bean1 {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static final class Bean2 {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) throws Exception {
final Bean1 bean1 = new Bean1();
final Bean2 bean2 = new Bean2();
bean1.setName("");
BeanUtils.copyProperties(bean2, bean1);
System.out.println("'" + bean2.getName() + "'"); // prints ''
bean1.setName(null);
BeanUtils.copyProperties(bean2, bean1);
System.out.println("'" + bean2.getName() + "'"); // prints 'null'
}
}
答案 3 :(得分:0)
纯Java SDK解决方案:
您可以使用Java Reflection。
编译示例(假设字段名称和类型相等)。
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws Exception {
final OldClass oldClass = new OldClass();
oldClass.setA("foo");
oldClass.setB("bar");
final NewClass newClass = new NewClass();
copyAllFields(oldClass, newClass);
System.out.println(newClass); // Prints: NewClass [a=foo, b=bar]
}
private static void copyAllFields(OldClass pOldClass, NewClass pNewClass) throws Exception {
final Field[] fields = pOldClass.getClass().getDeclaredFields();
for (Field fieldOldClass : fields) {
fieldOldClass.setAccessible(true);
final Object fieldValue = fieldOldClass.get(pOldClass);
final Field fieldNewClass = pNewClass.getClass().getDeclaredField(fieldOldClass.getName());
fieldNewClass.setAccessible(true);
fieldNewClass.set(pNewClass, fieldValue);
}
}
}
NewClass.java
public class NewClass {
private String a;
private String b;
@Override
public String toString() {
return "NewClass [a=" + a + ", b=" + b + "]";
}
}
OldClass.java
public class OldClass {
private String a;
private String b;
@Override
public String toString() {
return "OldClass [a=" + a + ", b=" + b + "]";
}
public void setA(String pA) {
a = pA;
}
public void setB(String pB) {
b = pB;
}
}