Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created January 11, 2012 16:00
Show Gist options
  • Save kmizu/1595340 to your computer and use it in GitHub Desktop.
Save kmizu/1595340 to your computer and use it in GitHub Desktop.
Get runtime type information of a Enumeration's subclass from a Value's instance.
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.
scala> object W extends Enumeration { val A = Value }
defined module W
scala> val V: Enumeration#Value = W.A
V: Enumeration#Value = A
scala> val VClass = V.getClass()
VClass: java.lang.Class[_ <: Enumeration#Value] = class scala.Enumeration$Val
scala> val outerM = VClass.getMethod("scala$Enumeration$Val$$$outer")
outerM: java.lang.reflect.Method = public scala.Enumeration scala.Enumeration$Val.scala$Enumeration$Val$$$outer()
scala> val WClass = outerM.invoke(V).getClass()
WClass: java.lang.Class[_ <: java.lang.Object] = class W$
@xerial
Copy link

xerial commented Jan 12, 2012

Thanks for the code. My problem is to create an Enumeration.Value from String (e.g., "A"):

object Fruit extends Enumeration { val Apple, Banana = Value }
class A {
  var fruit:Fruit.Value = Fruit.Apple
}

val a = new A
// What I want to do!
setByReflection(a, "fruit", "Banana") 
// Expected a.fruit == Fruit.Banana

I'm not sure how to create Fruit.Banana from String "Banana" without knowing enclosing Fruit class.

val f = a.getClass.getDeclaredField("fruit") 
f.set(a, Fruit.withName("Banana"))   // Possible only when we know about Fruit.class.  

val e = (Get Fruit class information using f.getType)
f.set(a,  (call e.withName("Banana") via reflection)) // This is what I need!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment