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$ .

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bf4073-31ecc.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bf4073-31ecc.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?