I found a solution. The main idea is to find companion object by value type. Here is my code:
def enumObjectForType[T <: Enumeration](implicit tt: TypeTag[T]) = {
val universeMirror = runtimeMirror(getClass.getClassLoader)
val objModule = typeOf[T].asInstanceOf[TypeRef].pre
.typeSymbol
.companionSymbol
.asModule
val companionMirror = universeMirror.reflectModule(objModule)
companionMirror.instance
}
def enumToMap[T <: Enumeration#Value](implicit tt: TypeTag[T]) = {
val ett = tt.asInstanceOf[TypeTag[Enumeration]]
val instance = enumObjectForType(ett).asInstanceOf[Enumeration]
instance.values map { v => (v.toString, v.id)} toMap
}
Usage:
object PROTOCOL_TYPE extends Enumeration{
type PROTOCOL_TYPE = Value
val HELLO = Value(0)
val ERROR = Value(1)
}
import PROTOCOL_TYPE._
println(enumToMap[PROTOCOL_TYPE]) // output is Map(HELLO -> 0, ERROR -> 1)