是否可以设置 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/