I've been searching in the official Groovy documentation how to replace a call like
MyOuterClass.this
inside a nested class MyInnerClass, but they don't seem to talk about this difficulty. And I did not find by Googling neither.
So, let's say I have this code :
class MyOuterClass {
class MyInnerClass {
}
}
How can I call the this pointer of MyOuterClass inside a method of MyInnerClass ?
Here is an attempt :
public class Outer {
def sayHello() {println "Hello !"}
public class Inner {
def tellHello(){
Outer.this.sayHello()
}
}
}
def objOuter = new Outer()
def objInner = new Outer.Inner()
objInner.tellHello()
and here the error stacktrace :
java.lang.NullPointerException: Cannot invoke method sayHello() on null object
at Outer$Inner.tellHello(inner_outer.groovy:5)
at Outer$Inner$tellHello.call(Unknown Source)
at inner_outer.run(inner_outer.groovy:12)
(I am using the Groovy 2.4.5 version).
The only problem is that you're not passing the outer object to your new Inner class statement, use this:
def objOuter = new Outer()
def objInner = new Outer.Inner(objOuter)
Instead of:
def objOuter = new Outer()
def objInner = new Outer.Inner()
And your code will works,
Hope this helps,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With