代码之家  ›  专栏  ›  技术社区  ›  soc Bhuwan Tripathi

如何通过将特征与反射混合来访问对象内的对象?

  •  4
  • soc Bhuwan Tripathi  · 技术社区  · 15 年前

    我怎样才能得到一个有反射的物体内的所有物体?

    请考虑以下代码:

    object MonthDay extends MyEnum {
      //Some important holidays
      object NewYear       extends MonthDay( 1,  1)
      object UnityDay      extends MonthDay(11,  9)
      object SaintNicholas extends MonthDay(12,  6)
      object Christmas     extends MonthDay(12, 24)
    }
    
    class MonthDay(month: Int, day: Int)
    
    trait MyEnum {
      val values: List[MonthDay] = this.getClass.getField("MODULE$")...
      val next: MonthDay = ...
      val previous: MonthDay = ...
    }
    
    //Of course the user can create his own MonthDays
    val myBirthDay = new MonthDay(month, day)
    
    if(!MonthDay.values.contains(myBirthDay)) "Well, I probably have to work"
    else "Great, it is a holiday!"
    

    我想有个特点( MyEnum )我可以将其混合到包含“枚举对象”的对象中,并使用方法返回它们的列表( def values: List[MonthDay] )或者迭代它们( def next: MonthDay def previous: MonthDay ) 不重复几次 (这绝对至关重要!).

    我的想法是 values 访问 MonthDay 对象并查找它们正在扩展的类的所有单例对象( 月日 )带着沉思。

    3 回复  |  直到 10 年前
        1
  •  1
  •   Community CDub    8 年前

    我的解决方案,基于 Landei's answer 将是:

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

    我觉得你不应该叫这个 MyEnum 因为枚举类型意味着一组封闭的值。

    (如果枚举值定义为 object (第页)

        2
  •  1
  •   Landei    15 年前
        3
  •  0
  •   Kevin Wright    15 年前

    您应该能够使用预先存在的Scala。 Enumeration 班级: http://www.scala-lang.org/api/current/scala/Enumeration.html

    它似乎非常接近您的用例!