How do I use Scala reflection to find all subclass

2019-08-18 05:50发布

问题:

Suppose I have a type, Result:

trait Result[+T] {

  def getValue: T

}

and a subtype of that trait, AnyValResult:

class AnyValResult(value: AnyVal) extends Result[AnyVal] {
  override def getValue: AnyVal = value
}

I want to be able to ask Scala's reflection library for all subtypes of the Result[_] type and have it return a collection that includes AnyValResult.

I've seen lots of people ask this question, and all of them seem to say that they did it using third-party tools. This was a few years ago. Short of reverse-engineering the third-party tools, is there a way to do this that was introduced in more recent versions of Scala? I would prefer not to have to reference some random project on Github if I can do it directly with reflection.

回答1:

Subclasses can be loaded/created dynamically at runtime (if trait is not sealed) so generally this can't be done directly with Java or Scala reflection. This is not question how recent verion of Scala is, this is how JVM works. Engine should load every class and check if the class extends the trait.

How do you find all subclasses of a given class in Java?

Is it possible to get all the subclasses of a class?