开发者

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

开发者 https://www.devze.com 2023-03-31 00:32 出处:网络
Suppose there are class/trait de开发者_开发知识库finitions as follows: trait T1 {} trait T2 {} abstract class A{}

Suppose there are class/trait de开发者_开发知识库finitions 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
0

精彩评论

暂无评论...
验证码 换一张
取 消