Consider the following code. Animals should have a unique ID. I want to dynamically verify (in a test) that all concrete subtypes of Animal have unique IDs. I want my test to fail if, for example, Cat and Fish both try to pass in uniqueId
= 2.
sealed trait Animal {
val uniqueId: Int
}
abstract class Mammal(val uniqueId: Int) extends Animal
abstract class Fish(val uniqueId: Int) extends Animal
case class Dog(age: Int, name: String) extends Mammal(1)
case class Cat(favouriteFood: String) extends Mammal(2)
case class Salmon(isCute: Boolean) extends Fish(3)
I'm using reflections to get the classes.
import org.reflections.Reflections
val reflections = new Reflections("package.blah")
val allSubtypes: Seq[Class[_ <: Animal]] = reflections.getSubTypesOf(classOf[Animal]).asScala.toList
val concreteSubtypes: Seq[Class[_ <: Animal]] = allSubtypes.filter(c => !Modifier.isAbstract(c.getModifiers))
I'm starting to suspect it might not be possible but would love to be wrong! I have the classes but no way to instantiate instances of them because all the constructors differ and I'm not sure if I can access the uniqueId
from just the class.
Aucun commentaire:
Enregistrer un commentaire