Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an instance of any class type, how to find out which parent class and/or traits it inherits from or implements?

Tags:

scala

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.

like image 553
Adrian Avatar asked Aug 25 '11 19:08

Adrian


1 Answers

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
like image 104
tenshi Avatar answered Oct 19 '22 08:10

tenshi