groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: Failing to change the value of a Java variable from wihtin a Groovy script (potential issue?)
Date Wed, 09 Mar 2016 13:37:17 GMT


On 08.03.2016 17:31, Thierry Hanser wrote:
[...]
> *In Groovy*
>
> println '1 = ' + x
> x = 'two'
> println '2 = ' + x
>
> *Output*:
>
> init x: one <- initial value assignement OK
>
> 1 = one <- successfully accessing ‘x’ from within the compiled script OK
>
>                  the Groovy script has picked up the value of the Java
> variable;
>
>                  the implicit getX() has been called
>
> 2 = one<- should be ‘two’ as per Groovy code (second line)
>
>                  but is unchanged ???

I think I know the problem...

When using a normal script your code above would have failed, because 
the binding does not contain x. But what exactly happens if the binding 
does not contain x? Groovy will ask the script class for a property of 
that name. Just to point it out very much: The property lookup is done 
only after binding is asked!

What happens in the set case then? The set case will always set a 
variable in the binding!

This explaines why for you "println '1 = ' + x " gives "one", but the 
important part is that then "x = 'two'" will leave that property 
untouched and goes directly to the binding. The subsequent "println '2 = 
' + x" will then get the value from the binding instead of asking for 
the property.

The solution would be to overwrite setProperty to first try setting the 
property on the script class, basically: a try with 
this.getMetaClass().setProperty(this, property, newValue); and a 
super.setProperty in the exception case.

And it seems the static compiler has big issues with handling a script 
base class

bye Jochen

Mime
View raw message