我们应该使用clone或BeanUtils.copyProperties以及原因 [英] Should we use clone or BeanUtils.copyProperties and why

查看:116
本文介绍了我们应该使用clone或BeanUtils.copyProperties以及原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过它的外观 - BeanUtils.copyProperties 似乎创建了一个对象的克隆。如果是这种情况,那么关于实现Cloneable接口的问题是什么(只有不可变对象是新的,因为可变对象有复制的引用)这是最好的,为什么?



<我昨天实现了cloneable,然后意识到我必须为非 String / Primative 元素提供自己的修改。然后我被告知我正在使用的 BeanUtils.copyProperties 。这两种实现似乎都提供了类似的功能。



谢谢

解决方案

Josh Bloch提供了一些相当不错的参数(包括你提供的参数)断言 Cloneable 从根本上是有缺陷的,而是支持复制构造函数。请参见此处



我还没有遇到过复制不可变对象的实际用例。您出于特定原因复制对象,可能是为了将一些可变对象集合到一个事务中进行处理,保证在处理单元完成之前不会改变它们。如果它们已经是不可变的,那么引用就像副本一样好。



BeanUtils.copyProperties 通常是更简洁的复制方式,无需改变你的类,而且它在合成对象时提供了一些独特的灵活性。



那就是说, copyProperties 并不总是一刀切。您可能在某些时候需要支持包含具有专门构造函数但仍可变的类型的对象。您的对象可以支持内部方法或构造函数来解决这些异常,或者您可以将特定类型注册到某些外部工具进行复制,但它无法到达某些地方甚至 clone()可以。这很好,但仍有限制。


By the looks of it - BeanUtils.copyProperties seems to create a clone of an object. If this is the case, and what with the concerns around implementing the Cloneable interface (Only immutable objects are new where as mutable objects have references copied) which is the best and why?

I yesterday implemented cloneable and then realised I had to provide my own modifications for non String/Primative elements. I was then informed about BeanUtils.copyProperties which I am now using. Both implementations seem to provide a similar functionality.

Thanks

解决方案

Josh Bloch provides some fairly good arguments (including the one you provided) asserting that Cloneable is fundamentally flawed, favoring a copy constructor instead. See here.

I haven't yet encountered a practical use case for copying an immutable object. You're copying objects for a specific reason, presumably to isolate some set of mutable objects into a single transaction for processing, guaranteeing nothing can alter them until that unit of processing is complete. If they're already immutable then a reference is as good as a copy.

BeanUtils.copyProperties is often a less intrusive way of copying without having to alter your classes to be supported, and it offers some unique flexibility in compositing objects.

That said, copyProperties is not always one-size-fits-all. You may at some point need to support objects containing types that have specialized constructors, but are still mutable. Your objects can support internal methods or constructors to work around those exceptions, or you can register specific types into some external tool for copying, but it can't reach some places that even clone() can. It's good, but still has limits.

这篇关于我们应该使用clone或BeanUtils.copyProperties以及原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆