How can I get all of the objects within an object with reflection?
Consider this code:
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!"
I want to have a trait (MyEnum
) which I can mix into the object holding my "enumeration objects" with methods to return a list of them (def values: List[MonthDay]
) or iterate over them (def next: MonthDay
or def previous: MonthDay
) without repeating myself a few times (this is absolutely crucial!).
The idea is that values
accesses the MonthDay
object and finds all singleton objects of the class they are extending (MonthDay
) with reflection.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…