sangria
sangria copied to clipboard
Support Java enumerations
It would be cool if they were supported out of the box. Otherwise you could easily add something like this
/**
* To be used similar to sangria derivation macros (though this is not a macro), e.g.
*
* // Java
* public enum JavaEnum { A, B }
*
* // Scala
* val GJavaEnum = deriveEnumTypeFromJavaEnumeration[JavaEnum]()
*/
def deriveEnumTypeFromJavaEnumeration[A](name: String = null)(implicit ev: ClassTag[A]): EnumType[A] = {
val javaEnumClass = ev.runtimeClass.asInstanceOf[Class[A]]
EnumType(if(name == null) javaEnumClass.getSimpleName else name,
values = javaEnumClass.getEnumConstants.map(value => EnumValue(value.toString, value = value)).toList)
}
Support for Java enums sounds reasonable. Though I would prefer to add support for it in DeriveEnumTypeMacro
macro rather than using runtime reflection.
I've been using this:
def enumType[T <: Enum[T]](values: Array[T]) =
EnumType(
values(0).getClass.getSimpleName,
Some(values(0).getClass.getName),
List(values: _*).map(item => EnumValue(item.name, value = item)))
implicit val someJavaEnumType: EnumType[SomeJavaEnum] = enumType(SomeJavaEnum.values)
Still runtime lookup of SomeJavaEnum.values()
though.