How can I get all of the objects within an object with reflection?
Consider this code:
object MonthDay extends MyEnum {
//Some important holidays
You should be able to use the pre-existing Scala Enumeration
class: http://www.scala-lang.org/api/current/scala/Enumeration.html
It seems to come very close to your use-case!
Something similar is done in Enumeration.populateNameMap: https://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_8_1_final/src/library/scala/Enumeration.scala
My solution, based on Landei's answer would be:
trait MyEnum{
def valsOfType[T:Manifest] = {
val c=implicitly[Manifest[T]].erasure
for {m <- getClass.getMethods
if m.getParameterTypes.isEmpty && c.isAssignableFrom(m.getReturnType)
} yield (m.invoke(this).asInstanceOf[T])
}
}
class MonthDay(month:Int,day:Int)
object MonthDay extends MyEnum {
//maybe you want to call this "holidays" instead
lazy val values = valsOfType[MonthDay]
val NewYear = new MonthDay( 1, 1)
val UnityDay = new MonthDay(11, 9)
val SaintNicholas = new MonthDay(12, 6)
val Christmas = new MonthDay(12, 24)
}
I don't think you should call this MyEnum
anymore, because an enumerated type implies a closed set of values.
(Doesn't work if the enumeration values are defined as object
s)