How does Scala get all the child objects that inherit trait

trait Base

object A extends Base // 
object B extends Base // 
object C extends Base // 
class D extents Base // 

object Base {
  //TODO  trait Base  object
  //TODO  akka actor  event  Base 
}
  • when using akka to throw a Event event, I want to inform all objects that inherit the attribute Base that they each perform their own actions on the event.
  • The desired effect of
  • now is that the events thrown by akka are uniformly distributed by the companion objects of Base , and verify that all inheritors of Base are object singletons.
Mar.04,2021

the reflection mechanism is needed here: use getSubTypesOf in the Java class library reflections to get all the subclasses, but to get their corresponding objects, you need to get the MODULE$ field through getField , and you can get the corresponding objects according to this field.

package com.gcusky.util.reflect

import org.reflections.Reflections
import scala.collection.JavaConverters._

object Base {
  def subObject[T](underlying: Class[T]): Seq[T] = {
    val reflects = new Reflections("com.gcusky.util.reflect")
    reflects.getSubTypesOf(underlying).asScala.map { sub =>
      sub.getField("MODULE$").get(null).asInstanceOf[T]
    }.toSeq
  }
}

because in Scala, two class files are generated after the singleton object and the accompanying object are compiled: Base.class and Base$.class . The Base$.class class has a constant field MODULE$ , whose type is the class type of the current class Test$ .

Menu