sangria icon indicating copy to clipboard operation
sangria copied to clipboard

Support Java enumerations

Open prismec opened this issue 7 years ago • 2 comments

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

prismec avatar Jul 07 '17 14:07 prismec

Support for Java enums sounds reasonable. Though I would prefer to add support for it in DeriveEnumTypeMacro macro rather than using runtime reflection.

OlegIlyenko avatar Jul 08 '17 16:07 OlegIlyenko

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.

dsilvasc avatar Nov 29 '17 00:11 dsilvasc