How to check if class type B extends class type A in groovy?
class A {
}
class B extends A {
}
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.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
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.
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
.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With