[英]Java: Copy properties from bean to an another one
I've these two classes: 我有这两节课:
public class ServiceConfiguration {
private String id;
private List<Parameter> parameters;
}
public class ConfigurationUpdateForm {
@NotEmpty private String id;
@NotEmpty @Valid private Collection<ConfigurationParameterForm> parameters;
}
I need to copy all properties from an ConfigurationUpdateForm
object to an ServiceConfiguration
object: 我需要将所有属性从
ConfigurationUpdateForm
对象复制到ServiceConfiguration
对象:
ServiceConfiguration serviceConfiguration = new ServiceConfiguration();
try {
BeanUtils.copyProperties(serviceConfiguration, configurationForm);
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it doesn't copy parameters
collection correctly. 但是它不能正确复制
parameters
集合。
What's failing is after copyProperties
, destinationbean.parameters
contains a list of ParameterTypeForm
instead of a list of Parameter
... 问题出在
copyProperties
之后, destinationbean.parameters
包含ParameterTypeForm
列表,而不是Parameter
...
Any ideas? 有任何想法吗?
BeanUtils.copyProperties(serviceConfiguration, configurationForm)
will just copy all the bean properties of one class to the other for all cases where the name is the same. 对于名称相同的所有情况,
BeanUtils.copyProperties(serviceConfiguration, configurationForm)
只会将一个类的所有bean属性复制到另一类。
As both classes contain the parameters
property, BeanUtils
will just copy the value. 由于两个类都包含
parameters
属性,因此BeanUtils
只会复制该值。
And that is exactly what is happening in your result, suddenly the parameters inside ServiceConfiguration
contains a list of ConfigurationParameterForm
objects. 这就是结果中正在发生的事情,突然,
ServiceConfiguration
中的参数包含一个ConfigurationParameterForm
对象的列表。
This is because the copying is only being done one level deep and also because at runtime nothing is preventing a List to contain objects of different classes than those you specified in the declaration. 这是因为复制仅进行了一层,而且在运行时也没有什么阻止List包含与声明中指定的对象不同类的对象。
In example: 例如:
public class Dog {
@Override
public String toString() {
return "I'm a dog";
}
}
public class Cat {
@Override
public String toString() {
return "I'm a cat";
}
}
public static void main(String[] args) {
List<Dog> dogs = new ArrayList<>();
dogs.add(new Dog());
addCat(dogs);
System.out.println(dogs);
}
public static void addCat(List cats) {
cats.add(new Cat());
}
Running the above code will result in: [I'm a dog, I'm a cat]
运行上面的代码将导致:
[I'm a dog, I'm a cat]
A possible solution would be to add your own mapping method that will map from one class to the other using getters and setters, but you will also need a mapping from: ConfigurationParameterForm
to Parameter
一种可能的解决方案是添加您自己的映射方法,该方法将使用getter和setter从一个类映射到另一个类,但是您还需要从以下映射:
ConfigurationParameterForm
到Parameter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.