Dark theme | Light theme

January 15, 2010

Groovy Goodness: Is Object in Class Hierarchy

With Groovy's in keyword we can check if an object is assignable for a class in the class hierarchy (noted by Andrey Paramonov - see comment section). This way we can check if the object is an instance of a certain class or one of the parents of the class or to be more specific, if the class is assignable for the class or parent classes. This can also be useful when checking if an exception for example is part of an exception hierarchy.

class Shape { }
class Circle extends Shape { }
class Square extends Shape {}

// Create Square instance.
def square = new Square()

assert square in Shape
assert square in Square
assert !(square in Circle)

[Shape.class, Square.class].each {
    assert square in it