Java:修改参数时使用 .clone() 的替代方案?

发布于 2025-01-08 01:46:01 字数 376 浏览 1 评论 0原文

所以我总是被告知修改方法的参数是不好的做法(至少当它不直观时)。通常我会使用一些简单的内容,例如:

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉酒的小男人 2025-01-15 01:46:01

从安全角度来看(这通常让我们保持诚实),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 (except HttpCookie - it's mutable but final). 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).

风吹短裙飘 2025-01-15 01:46:01

如果有 SomeClass 类型的变量 XY,恰好包含一个复制构造函数,并且有人说 X = new SomeClass( Y); 当 Y 为非空时,X 将收到一个 SomeClass 类型的新实例,无论 的实际类型如何>Y。相比之下,如果使用 X = (SomeClass)Y.clone()并且 Y 的实际类型正确实现 clone,则将接收与 Y 类型相同的对象。哪种方法“更好”将取决于程序对派生类型的行为方式。

If one has variables X and Y of type SomeClass which happens to include a copy constructor, and one says X = new SomeClass(Y); when Y is non-null, then X will receive a new instance which will be of type SomeClass, regardless of the actual type of Y. By contrast, if one instead uses X = (SomeClass)Y.clone(), and the actual type of Y implements clone correctly, one will receive an object of the same type as Y. Which approach is "better" will depend upon how the program is supposed to behave with derived types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文