【发布时间】:2016-12-13 16:00:35
【问题描述】:
我的目标是将一个对象的字段复制到另一个对象中,但仅限于那些不为空的。我不想明确分配它。更通用的解决方案将非常有用且更易于维护,即用于在 REST API 中实现 PATCH,您只允许提供特定字段。
我看到了这个类似的帖子,我正在尝试从这里实现一些想法:Helper in order to copy non null properties from object to another ? (Java)
但程序执行后对象不会以任何方式改变。
所以这是我创建的示例类,例如:
class Person {
String name;
int age;
Pet friend;
public Person() {
}
public Person(String name, int age, Pet friend) {
this.name = name;
this.age = age;
this.friend = friend;
}
// getters and setters here
}
class Pet {
String name;
int age;
public Pet(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters here
}
这是我重写的 copyProperty 方法:
import org.apache.commons.beanutils.BeanUtilsBean;
import java.lang.reflect.InvocationTargetException;
public class MyBeansUtil extends BeanUtilsBean {
@Override
public void copyProperty(Object dest, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
if(value == null) return;
super.copyProperty(dest, name, value);
}
}
...这里是我尝试在一些示例上对其进行测试的地方:
public class SandBox {
public static void main(String[] args) {
Person db = new Person("John", 36, new Pet("Lucy", 3));
Person db2 = new Person("John", 36, new Pet("Lucy", 2));
Person db3 = new Person("John", 36, new Pet("Lucy", 4));
Person in = new Person();
in.age = 17;
in.name = "Paul";
in.friend = new Pet(null, 35);
Person in2 = new Person();
in2.name = "Damian";
Person in3 = new Person();
in3.friend = new Pet("Lup", 25);
try {
BeanUtilsBean notNull =new MyBeansUtil();
notNull.copyProperties(db, in);
notNull.copyProperties(db2, in2);
notNull.copyProperties(db3, in3);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
不幸的是,原始对象 db、db1、db2 保持不变。我在这里做错了吗?
【问题讨论】:
-
将类声明的访问修饰符更改为 public 以使其工作。 public class Person { } 会解决这个问题
-
感谢您的回答 - 我已经找到了一个对我更好的解决方案,因为我避免依赖 apache.commons.beanutilsbean。现在我知道这两种方式:)
-
@kiedysktos 我有一个类似的用例,很想知道还有什么其他解决方案适合你。如果你能详细说明,那就太好了:)
-
不幸的是,接受的答案代表了我尝试过的唯一方法