How to access a field's value via reflection (Scala 2.8)

前端 未结 5 1981
北海茫月
北海茫月 2021-02-08 00:18

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:

<
5条回答
  •  离开以前
    2021-02-08 00:40

    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]
    

提交回复
热议问题