I want to automatically convert/coerce strings into Scala Enumeration Values, but without knowing beforehand what Enumeration subclass (subobject?) the declaration is from.
So, given:
object MyEnumeration extends Enumeration {
type MyEnumeration = Value
val FirstValue, SecondValue = Value
}
and
class MyThing {
import MyEnumeration._
var whichOne: MyEnumeration = FirstValue
}
how would I implement the following?
val myThing = new MyThing()
setByReflection(myThing, "whichOne", "SecondValue")
What I'm finding is that when I get the class of MyThing.whichOne (via java.lang.Field), the return is 'scala.Enumeration$Value', which isn't specific enough for me to enumerate the names of all the possible values.
The specific type is lost at runtime however you can capture it at compile time through implicits. You can provide an implicit in your enum like the following.
You could also do the following as well if the type system is unable to resolve your enum to apply the correct implicit in your usages you can default to using polymorphism if and provide a setter like the following.
Check out my EnumReflector, which will tell you all about enum field types, as long as they're declared in the package scope (no inner-class enums, function scope enums).
You need to supply it the scala type of the enum field (which can found through scala's reflection interface) (see below for how to get this from a Class[_])
How to get the enumObjectType?
... now you need to use Java reflection to find the same method for this class. Scala has instance reflection but requires you do reflection on the instance at runtime (which is slow). Better to get a handle to Java reflection invoke method:
Starting with your
you can now get the object's enum field and interpret its name or id through the reflector:
Support functions:
There's a unit test in the project that demonstrates it.