gpt4 book ai didi

java - 选择 Java 函数调用中的按值传递行为

转载 作者:行者123 更新时间:2023-11-29 04:46:46 25 4
gpt4 key购买 nike

当我将我的对象传递给方法或函数时,是否可以设置我的 Java 项目(或其某些子集)的默认行为来制作对象的副本?

想要这种行为的原因是我正在编写大量测试来检查两个函数是否产生相同的返回值。如果我将 ObjectA(属性计数初始化为 3)传递给 decrementCount() 函数,当它返回对象时我将看到 (ObjectA.count -> 2),而在调用第二个函数之后,对象现在是 (ObjectA.count -> 1)

我想实现按值传递而不是按引用传递。

最佳答案

Is it possible to set the default behavior of my Java project (or some subset of it) to make copies of my objects when I pass them into methods or functions?

不,Java 只是按值传递。 Java的变量只能是原语和引用。它们不能是对象,并且您不能强制复制它们(不显式复制它们)。

If I pass in ObjectA (where a property count is initialized to 3) to function decrementCount() than when it returns the object I will see (ObjectA.count -> 2), while after calling the second function the object is now (ObjectA.count -> 1).

我建议您为每个测试重新创建对象。如果你想防止修改,你可以测试它没有被修改。

I would like to achieve pass-by-value rather than pass-by-reference.

这实际上是您唯一的选择。但是,引用中值的副本不是深副本。

关于java - 选择 Java 函数调用中的按值传递行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36842620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com