How to access objects within an object by mixing in a trait with reflection?

前端 未结 3 1933
遇见更好的自我
遇见更好的自我 2020-12-11 07:28

How can I get all of the objects within an object with reflection?

Consider this code:

object MonthDay extends MyEnum {
  //Some important holidays
          


        
相关标签:
3条回答
  • 2020-12-11 07:58

    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!

    0 讨论(0)
  • 2020-12-11 08:08

    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

    0 讨论(0)
  • 2020-12-11 08:14

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

    0 讨论(0)
提交回复
热议问题