Groovy(或Java)-通过引用传递给包装对象 [英] Groovy (or Java) - Pass by reference into a wrapper object

查看:78
本文介绍了Groovy(或Java)-通过引用传递给包装对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java(或Groovy)中是否可以通过引用将对象传递给包装对象(即List或Map)?

Is it possible in Java (or Groovy) to pass an object by reference into a wrapper object (ie: List or Map)?

示例代码(在Groovy中):

Example code (in Groovy):

def object = null
def map = [object: object]
object = new Object()

不幸的是,即使object变量不存在,map.object仍为null,因此显然,地图的原始创建是通过值完成的,而不是通过引用完成的.

Unfortunately map.object remains null even though the object variable doesn't, so obviously the original creation of the map was done by value not by reference.

是否可以通过引用创建列表或地图,以便当列表或地图外部的对象发生更改时,更改会反映在包装对象内部?

Is it possible to create a List or Map via references so that when the object outside the List or Map changes the change is reflected inside the wrapper object?

推荐答案

您可以使用闭包,但是需要调用它们:

You can with closures, but they need to be invoked:

def object = null
def map = [object: { object }]
object = new Object()

assert map.object() != null

这篇关于Groovy(或Java)-通过引用传递给包装对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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