I came across an interesting problem with someone’s groovy code, and was able to reproduce the problem. In the interest of not having to bang my head against this again, I repeat the problem for you:
public class Parent
{
def varName
def gimmeVarName()
{
return varName
}
}
public class Child extends Parent
{
def varName = "Hello World"
}
public class Runner
{
static void main(args)
{
def c = new Child()
println c.gimmVarName()
}
}
Now, what do you think happens here? I expected it to print out “Hello World.” I got a NullPointerException. Looking closer, however, the answer is fairly obvious. The “def varName” inside Parent defines a variable for itself, and the Child defines a new variable, with the same name, in the outer scope. I was able to fix this issue two ways. First, the bad way, by fixing Parent:
public class Parent
{
def varName
def gimmeVarName()
{
return getVarName()
}
}
Now, by calling the auto-generated bean method, it starts at the scope of Child and finds it immediately — returning me a string. That must mean when I say return varName it’s not using the accessor function, but rather accessing the variable directly (which is, arguably, the correct thing to do).
Of course, the way to properly fix it is to use proper constructors to set those kinds of things up:
public class Child extends Parent
{
Child()
{
varName = "Hello World"
}
}
Then, the original function works fine. It seemed really weird at the time, but makes perfect sense now.
0 comments ↓
There are no comments yet...Kick things off by filling out the form below.
Leave a Comment