Search code examples
scalareflectionenumerationclassname

scala reflection get class of enumaration value


Assume we have

class User(val name: String, val role: UserRole.Value)

class UserRole extends Enumeration {
    val Admin, User = Value
}

val u = new User("root", UserRole.Admin)

how to get Class[_] "class UserRole" when

u.role.getClass

return "scala.Enumeration.Value"


Solution

  • Neither new User("root", UserRole.Admin) nor role: UserRole.Value make sense, because UserRole is not a value. Normally, Enumeration is extended by objects, not classes.

    Something like

    val field = classOf[Enumeration#Value].getDeclaredField("outerEnum")
    field.setAccessible(true)
    val enum = field.get(u.role)
    enum.getClass // if you want specifically the class
    

    should work (at least for the current versions; outerEnum is not part of the API!)