Java:修改参数时使用 .clone() 的替代方案?
所以我总是被告知修改方法的参数是不好的做法(至少当它不直观时)。通常我会使用一些简单的内容,例如:
public Type method(Type Object) {
Type otherObject = Object.clone();
// do stuff to otherObject
return otherObject;
}
这是我经常做的事情,尽管很少做。有更好的方法来做到这一点吗? 例如,一种使 java 按值传递而不是按引用传递的方法,以便修改参数不会对我的类的用户产生不可预见的后果。 除了不太清楚(某种程度)之外,克隆方法大概在 O(n) 时间内运行,所以不必这样做会很好。
谢谢!
So I've always been told that it's bad practice to modify arguments to methods (at least when it's not intuitive). Normally I'd use something simple, like:
public Type method(Type Object) {
Type otherObject = Object.clone();
// do stuff to otherObject
return otherObject;
}
This is something I do quite frequently, albiet sparingly. Is there a nicer way to do this?
For example, A way to make java pass by value, instead of by reference, so that modifying the argument wouldn't have unforseen consiquences for users of my classes.
Besides being less clear(sort of) clone methods presumably run in O(n) time, so not having to do this would be nice.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从安全角度来看(这通常让我们保持诚实),
clone
通常是错误的做法(HttpCookie
除外 - 它是可变的,但final
代码>)。如果该对象有一个不可靠的实现,那么您也将复制它。您能做的最好的事情就是使
Type
不可变。问题就消失了。无需复制。如果它是一个可变值,只需构造一个副本 -
new Type(object)
或其他。请记住,应在检查对象内容是否有效之前完成复制,以避免检查时间到使用时间错误(TOCTOU/TOC2TOU)。From a security point of view (and that usually keeps us honest),
clone
is usually the wrong thing to do (exceptHttpCookie
- it's mutable butfinal
). If the object has a dodgy implementation, you'll be copying that as well.The best thing you can do is make,
Type
immutable. The problem goes away. No need to copy.If it is a mutable value, just construct a copy -
new Type(object)
or whatever. Remember to the copying should be done before checking that the contents of the object are valid, to avoid time-of-check to time-of-use bugs (TOCTOU/TOC2TOU).如果有
SomeClass
类型的变量X
和Y
,恰好包含一个复制构造函数,并且有人说X = new SomeClass( Y);
当 Y 为非空时,X
将收到一个SomeClass
类型的新实例,无论的实际类型如何>Y。相比之下,如果使用
X = (SomeClass)Y.clone()
,并且 Y 的实际类型正确实现clone
,则将接收与Y
类型相同的对象。哪种方法“更好”将取决于程序对派生类型的行为方式。If one has variables
X
andY
of typeSomeClass
which happens to include a copy constructor, and one saysX = new SomeClass(Y);
when Y is non-null, thenX
will receive a new instance which will be of typeSomeClass
, regardless of the actual type ofY
. By contrast, if one instead usesX = (SomeClass)Y.clone()
, and the actual type of Y implementsclone
correctly, one will receive an object of the same type asY
. Which approach is "better" will depend upon how the program is supposed to behave with derived types.