Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type from Scala reflection

Suppose that I have:

trait A

class B extends A

compiled into class files. Later I load those using reflection:

val a = Class forName "A"
val b = Class forName "B"

Could anyone tell me how to check whether b is the subtype of a?

like image 705
classicalist Avatar asked May 20 '26 22:05

classicalist


2 Answers

Use the isAssignableFrom method in Class:

a isAssignableFrom b

This returns true if b is a subclass/subinterface of a or b == a.

like image 173
Moritz Avatar answered May 22 '26 13:05

Moritz


You can just call the getInterfaces method on b and iterate through the array to see if any of them equals a.

like image 38
Kim Stebel Avatar answered May 22 '26 15:05

Kim Stebel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!