0

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"

Igor Yudnikov
  • 434
  • 1
  • 6
  • 14

1 Answers1

2

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!)

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • I'm using Scala 2.11 and I needed to use `getDeclaredField("scala$Enumeration$$outerEnum")` to make it work. – mephi42 Apr 09 '18 at 11:19