Scala: get mixin interfaces at runtime

I need to get all the interfaces at runtime from this class (all loaded in ClassLoader).

For example, if a class was declared as follows:

trait B trait C trait D class A extends B with C with D 

I want to get this information at runtime: A depends on B and C and D. Java getInterfaces () (or interfaces () from the clapper library) gives only the first dependency, namely: A depends on B.

Is there any way to achieve this?

I think a reflection, but I do not know how?

+4
source share
2 answers

This question answers:

 import scala.reflect.runtime.universe._ trait B trait C class A extends B with C val tpe = typeOf[A] tpe.baseClasses foreach {s => println(s.fullName)} // A, C, B, java.lang.Object, scala.Any 


It works in REPL, but when I injected the code into a Scala script file and executed it, it no longer ran:

 typeOf[A] // Compiler error: No TypeTag available for this.A 

Using weakTypeTag instead did not help either

 weakTypeTag[A] // Runtime error: scala.reflect.internal.FatalError: // ThisType(free type $anon) for sym which is not a class 

I got the same behavior with Scala 2.10.0, 2.10.1 and 2.11.0-M2.

+2
source

The solution I found with reflection:

 import scala.reflect.runtime.{universe => ru} val mirror = ru.rootMirror val t = m.staticClass(classString).typeSignature t.baseClasses 
+2
source

Source: https://habr.com/ru/post/1480451/


All Articles