Suppose there are class/trait definitions as follows:
trait T1 {}
trait T2 {}
abstract class A{}
class B {}
class C extends A with T1 with T2 {}
val b = new B with T1
val c = new C
Given the instance of b and c, how do I get their inheritance information (i.e. to know that b implements T1, and c implements A, T1 and T2) ?
Thanks for your help.
If you don't know the type of the object (you have some AnyRef) and just want to test whether it's instance of some class or trait, then you can use isInstanceOf:
b.isInstanceOf[T2]
If you then want to cast it to that type, then use asInstanceOf
b.asInstanceOf[T1]
From the other hand, if you don't know what you are searching for, then you can try to use Java reflection. To get list of implemented traits and interfaces use:
c.getClass.getInterfaces
To get superclass use:
c.getClass.getSuperclass
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