简体   繁体   English

如何在Java中将对象从一种类型复制到另一种类型?

[英]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.

相关问题 从一个 object 复制 not null and not empty fields 到 java 中的另一个 object 相同类型(对象是相同类型) - Copy not null and not empty fields from one object to another object of the same type(Objects are same type) in java 将值从一种类型的集合复制到另一种类型的集合中 java 8 - copy value from set of one type to set of another type in java 8 将一个 Java 对象复制到另一个对象 - Copy one Java object to another Java:将属性从一个对象实例复制到另一个对象实例 - Java: Copy attributes from one object instance to another? 将 java 对象/类从一个类加载器复制到另一个类加载器 - Copy java object/class from one classloader to another classloader 如何将输入数据从一个文件复制到另一个文件? 在 java - how to copy input data from one file to another one? in java 如何将字段从一个 object 复制到另一个,包括 collections - How to copy fields from one object to another including collections 如何在Java中将数据从一个对象列表复制到另一个对象? - How to copy data from one list of objects to another in java? 如何将属性从一个Java bean复制到另一个? - How to copy properties from one Java bean to another? 如何使用Java将文件从一个文件夹复制到另一个文件夹? - How to copy files from one folder to another using Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM