2

When I'm calling a function in Groovy, how do I determine the class of the caller?

For example, I want to know what the class of foo is, inside the printFoo() function:

foo.printFoo()

def printFoo() {
  print(this.class)
}

And this should print out the class of foo

reectrix
  • 7,999
  • 20
  • 53
  • 81
  • Not sure about Groovy specific, but Java provides a way which is specified in [this question](http://stackoverflow.com/questions/421280/how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection) – christopher Mar 31 '15 at 16:53
  • `this.getClass().getName()` ? – sebnukem Mar 31 '15 at 17:26
  • 2
    @christopher That technique is going to be problematic, particularly with Groovy's dynamic dispatch because there are going to be potentially a lot of frames between the caller and the destination. – Jeff Scott Brown Apr 01 '15 at 12:16

2 Answers2

3

I don't know of any Groovy-specific way, but you can get the class name with object.getClass().name. Is that what you are looking for?

If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:

object instanceof Date

or to check if the class of an object is exactly a particular class (not a subclass of it), use:

object.getClass() == Date

There's also the in operator: object in Date

sebnukem
  • 8,143
  • 6
  • 38
  • 48
1

The language and the runtime don't provide a reliable mechanism to do what you are asking about. You can do some pokey jiggery inspecting stack frames but that is really detailed low level stuff and won't really be reliable for a number of reasons. The short answer is, the language just doesn't support it.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47