Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if class type A extends class type B in groovy

Tags:

groovy

How to check if class type B extends class type A in groovy?

class A {
}

class B extends A {
}
like image 352
Michal Z m u d a Avatar asked Sep 27 '13 13:09

Michal Z m u d a


People also ask

How do you know if a class extends another class?

If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class) Class#isAssignableFrom(Class) also returns true if both classes are same. To find if an object is instance of a class use instanceof operator.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do you check if an object is a certain subclass?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.


2 Answers

Groovy's in operator will test for the is a relationship when the right-hand argument is a Class, so B in A is equivalent to Java's A.isAssignableFrom(B). This also works for objects. new C() in A is equivalent to new C() instanceof A.

Example

class A {}
class B extends A {}
class C extends B {}

assert C in A // C inherits from A

interface I {}
interface J extends I{}

assert J in I // J extends I

class D implements I {}

assert D in I // D implements I

final o = new C()
assert o in A // o is an instance of A
like image 152
Justin Piper Avatar answered Sep 22 '22 15:09

Justin Piper


You can do it the same way as in Java:

A.isAssignableFrom(B)

See another Justin Piper's answer for Groovy in operator.

It seems awkward, but it means that B is a subclass of A. The height of inheritance hierarchy does not matter. It works also in case of interfaces.

Example

class A {}
class B extends A {}
class C extends B {}

assert A.isAssignableFrom(C) // C inherits from A

interface I {}
interface J extends I{}

assert I.isAssignableFrom(J) // J extends I

class D implements I {}

assert I.isAssignableFrom(D) // D implements I
    

See Class.isAssignableFrom.

like image 27
Grzegorz Żur Avatar answered Sep 22 '22 15:09

Grzegorz Żur