My requirement is to get a NEW instance every time when I access the value in a MAP.
MyObject {
def type
}
def myMap = [
"key1" : new MyObject()
]
def obj1 = myMap.get("key1")
def obj2 = myMap.get("key1")
Can obj1 and obj2 be two different instances? How will it behave if executed/accessed parallelly?
don't know what your use case is, but I guess I have the answer to your question:
def myMap = [
"key1" : new MyObject()
]
Just first instantiates a new object and then stores this object in the map. So every time you access it, you get the same object.
To create the behavior you describe, you need to add something dynamic to your map - a closure!
def myMap = [
"key2" : {-> new MyObject()}
]
but now a myMap.get("key2")
still returns always the same - a closure. But if you execute it by calling myMap.get("key2")()
(or short myMap.key2
) you get a different object each time!
Unfortunately, this is a close as you will get. I hoped to do a trick with a key called getKey3
- I hoped that Groovy would call this "getter" when accessing key3
but this seems not to be the case.
There are other "tricks" in Groovy which could help you to achieve your goal (like MetaProgramming) but I guess there is a better solution if we would know your use case.