How to access a field's value via reflection (Scala 2.8)
As others have mentioned, the reflection methods return Object
so you have to cast. You may be better using the method that the Scala compiler creates for field access rather than having to change the visibility of the private field. (I'm not even sure if the name private field is guaranteed to be the same as that of the accessor methods.)
val foo = new Foo
val method = foo.getClass.getDeclaredMethod("name")
val value = method.get(foo).asInstanceOf[String]
getDeclaredField
is a method of java.lang.Class
.
You have to change foo.getDeclaredField("name")
to foo.getClass.getDeclaredField("name")
(or classOf[Foo].getDeclaredField("name")
) to get the field.
You can get the type with getType
method in class Field
but it won't help you because it returns Class[_]
. Given than you know that the type is a String you can always cast the value returned using field.get(foo).asInstanceOf[String]