Loading...

Friday, 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
}

6 comments:

Anonymous said...

is this better(performance) than instanceof or is the same?

thanks

Chris Broadfoot said...

I'd hazard a guess at worse performance.

'in' actually maps to the method 'isCase' so there's at least an extra method call there.

mrhaki said...

@Chris and @Anonymous: my guess is also that performance is worse than instanceof method.

David said...

Don't ask that question yet! Don't guess at performance and don't develop idioms in your head based on "this has better performance." If you are using Groovy, write to communicate intent. When you are done, find the slow points in your app and tune from there.

--David Mitchell
http://www.withaguide.com

Andrey Paramonov said...

Don't compare 'in' with 'instanceof', compare it with 'isAssignableFrom'. That means with 'in' you can do something like this:

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

mrhaki said...

@Andrey Paramonov: thank you for your comment. I've included your comment in the blog post.

Post a Comment