[英]How to copy an object from one type to another in Java?
I have the following situation: Class A and Class B have completely identical source code. 我有以下情况:A类和B类具有完全相同的源代码。 I have an array from A and have to convert it to array from B, in order to pass it as a parameter in method whom argument is from type B.
我有一个来自A的数组,并且必须将它从B转换为数组,以便将其作为参数传递给参数,该参数来自类型B.
A[] foo = new A[] ;
//here getBar in certain situations accepts B[], but foo is always A[]
bar = BarFactory.getBar(foo);
I know it is a strange scenario but I am writing some kind of adapter for an existing infrastructure, which have really strange architecture I cannot see any way to sidestep this conversion. 我知道这是一个奇怪的场景,但我正在为现有的基础架构编写某种适配器,它有非常奇怪的架构我无法看到任何方式来回避这种转换。 I cannot change the source of B and cannot have any hard reference to B. I also cannot make another methods to A because it have to be exact copy of B.
我无法改变B的来源,也不能对B进行任何硬性引用。我也不能为A制作另一种方法,因为它必须是B的精确副本。
What would be the best way to make that conversion? 进行转换的最佳方式是什么? Is there some kind of pattern for creating a Convertor class or something similar to this?
是否有某种模式用于创建转换器类或类似的东西?
I know that the question may sound stupid but please don't "kill" me. 我知道这个问题可能听起来很愚蠢,但请不要“杀死”我。 I just want to do it in the best way.
我只想以最好的方式做到这一点。
It might depend on how complex A and B are, but since you are positive that the code is the same, copying all the properties of an object A to a new object B should produce the expected result. 它可能取决于A和B的复杂程度,但由于您肯定代码是相同的,因此将对象A的所有属性复制到新对象B应该会产生预期的结果。
Apache has a project commons-beanutils
that might help you in this task: Apache有一个项目
commons-beanutils
可以帮助你完成这项任务:
BeanUtils.copyProperties(foo[i], newFoo[i]);
You can do it like this : 你可以这样做:
B[] b = (B[]) foo
Where foo is an array of class A 其中foo是A类数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.