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

前端 未结 5 2068
北海茫月
北海茫月 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:43

    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]

提交回复
热议问题