Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to the outer class this?

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).

like image 433
loloof64 Avatar asked Oct 27 '25 23:10

loloof64


1 Answers

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,

like image 89
albciff Avatar answered Oct 31 '25 11:10

albciff