Consider the following code:
class Foo(var name: String = "bar")
Now i try to get the value and the correct type of it via reflection:
val foo = new Foo
val field = foo.getClass.getDeclaredField("name")
field.setAccessible(true)
//This is where it doesn't work
val value = field.get(????)
I tried things like field.get(foo), but that just returns an java.lang.Object but no String. Basically I need the correct type, because I want to invoke a method on it (e. g. toCharArray).
What is the suggested way to do that?
AFAIK, reflection always work with Object, and you have to cast the results yourself.
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.)getDeclaredField
is a method ofjava.lang.Class
.You have to change
foo.getDeclaredField("name")
tofoo.getClass.getDeclaredField("name")
(orclassOf[Foo].getDeclaredField("name")
) to get the field.You can get the type with
getType
method in classField
but it won't help you because it returnsClass[_]
. Given than you know that the type is a String you can always cast the value returned usingfield.get(foo).asInstanceOf[String]
This is how one can get list of fieldnames and its value of a case class:
First, using reflection, get fields info as follows -
How to use it?