如何通过反射访问字段的值(Scala 2.8) [英] How to access a field's value via reflection (Scala 2.8)

查看:356
本文介绍了如何通过反射访问字段的值(Scala 2.8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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(????)

我尝试了诸如field.get(foo)之类的东西,但是只返回一个java.lang.Object但没有String.基本上,我需要正确的类型,因为我想在其上调用一个方法(例如toCharArray).

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).

建议的方法是什么?

推荐答案

正如其他人所提到的,反射方法返回Object,因此您必须进行转换.使用Scala编译器创建的用于字段访问的方法,而不是必须更改私有字段的可见性,可能会更好. (我什至不确定名称私有字段是否保证与访问器方法的名字相同.)

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]

这篇关于如何通过反射访问字段的值(Scala 2.8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆