groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: dynamically attached object/added ivar
Date Fri, 12 Feb 2016 19:37:11 GMT


On 12.02.2016 12:20, ocs.cz wrote:
> Hello there,

hi, long time no see ;)

> have we in Groovy an API which would serve as a reliable replacement of “dynamically
attached objects” or “dynamically added ivars” of other APIs? I mean a way to reasonably
implement something like "x_attach" and "x_attached" here:
>
> def foo=... // any object of any class, typically some Map, but not necessarily
> def tag=... // any object of any class, possibly even a class itself
>
> foo.x_attach(tag)
> def bar=foo // just to emphasize the attachment is object's, not variable's property
>
> ... throughout the code, "foo" and "bar" can be used normally, all APIs and libraries
etc. work with it the very same way they would without "x_attach" ...
>
> assert bar.x_attached().is(tag) // but later, I can get the attached object
>
> When the object foo/bar gets garbage-collected, it's attachment loses an active link
and (presumed it is not referenced from another place) gets garbage-collected too. Due to
this demand, it is rather inconvenient to simulate the attachments by a static map indexed
e.g., by System.identityHashCode(foo), for -- far as I know at least -- there is no convenient
API to determine when a generic object (whose finalize I cannot override) goes poof (and thus
its attachment should be removed from the map).

what you can do easily in Groovy is something like

def foo = [:]
def tag = something here
foo.x = tag
def bar = foo

assert bar == tag
assert foo.x == bar

  BUT:

tag = something else
assert bar != tag
assert foo.x == tag // fails now

 From what I understand you want the last condition to be true as well. 
If yes, then it gets difficult, if no, well then foo can be any Map or 
Expando, the usage in the case of Expando is just like above, only the 
init is different of course. And of course this is still without the 
memory requirement. Though you could use a map which uses WeakReference 
for the values. Apache Commons ReferenceMap comes here to my mind though.

bye Jochen

Mime
View raw message